发布方法405错误

时间:2016-12-19 19:50:13

标签: python flask

我对API有一个相当中等的理解,而不是试图将我从API获得的信息存储到网上。

这个非常简单的代码:

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)

没有给我任何东西(405错误除外)。

有人可以解释为什么我的POST方法不起作用吗?

2 个答案:

答案 0 :(得分:1)

虽然我不完全确定你做了什么,但我认为你做了什么:

您访问了浏览器中的/temperature页面,默认情况下为GET - 请求。

然后您返回405 Method Not Allowed Error,因为您的路由明确要求通过HTTP - POST方法访问该页面。

@app.route('/temperature', methods=['POST'])修改为@app.route('/temperature', methods=['POST', 'GET']),您应该没问题。

答案 1 :(得分:0)

我会在/ r / flask发布我的回答,仅供后人使用。

代码中的行:String表示您通过POST将HTML表单中的数据提交到视图。

如果没有表单,那么zipcode = request.form['zip']什么都不做,很可能会引发错误。考虑到我的逻辑中没有任何路由指向任何HTML,我猜这是问题。

如果您尚未为用户构建表单以提交邮政编码,则可以将其构建到路线逻辑中。例如,你可以这样做:

request.form['zip']

然后,您可以使用@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 查看该邮政编码的数据。

(作为旁注,公开分享您的API密钥通常是不明智的。您可能希望生成新密钥。)