Reputation: 51
I have a decently intermediate understanding of APIs, and am not trying to host information I've got from APIs onto the web.
This incredibly simple code:
from flask import Flask, request, render_template
import requests
app = Flask(__name__)
@app.route('/temperature', methods=['POST'])
def temperature():
zipcode = request.form['zip']
r = requests.get('http://api.openweathermap.org/data/2.5/weather?zip=' +zipcode+',us&appid=9b56b06ab4c7f06821ccf55e3e10fce5')
json_obj = r.text
return json_obj
@app.route('/')
def index():
return 'hi'
if __name__ == '__main__':
app.run(debug=True)
Is not giving me anything (except the 405 error).
Can someone please explain why my POST method is not working?
Upvotes: 0
Views: 1134
Reputation: 46
I'll post my answer from /r/ flask here, just for posterity.
the line in your code: zipcode = request.form['zip']
implies that you are submitting data from an HTML form to the view via a POST.
If there is no form, then request.form['zip']
does nothing, and is most likely raising the error. Considering that I see no route in your logic there that points to any HTML, I'm guessing that's the issue.
If you have not built a form for the user to submit the zip code, then you could build it into the route logic. For example, you could do:
@app.route('/temperature/<zipcode>')
def temperature(zipcode):
# add some kind of validation here to make sure it's a valid zipcode
r = requests.get('http://api.openweathermap.org/data/2.5/weather?zip=' +zipcode+',us&appid=DONT_SHARE_YOUR_API_KEY')
json_obj = r.text
return json_obj
You could then use http://127.0.0.1:5000/temperature/20003
to see the data for that zip code.
(as a side note, it's often unwise to publicly share your API keys. you may want to generate a new key.)
Upvotes: 0
Reputation: 13107
While I'm not entirely sure what you have done, here's what I think you did:
You accessed the /temperature
page in your browser which is by default a GET
-Request.
You then get returned a 405 Method Not Allowed Error, because your route explicitly requires that the page will be accessed via the HTTP-POST
Method.
Modify @app.route('/temperature', methods=['POST'])
to @app.route('/temperature', methods=['POST', 'GET'])
and you should be fine.
Upvotes: 1