使用请求 returns 404 将 JSON 发布到 Flask 视图
Posting JSON to Flask view using Requests returns 404
我想使用 Requests post JSON 数据到 Flask 视图。但是,当我发出请求时,我得到了 404。为什么我的代码不起作用?我如何正确postJSON数据?
@app.route('/foo/<foo>', defaults={'foo': 'foo'})
@app.route('/foo/<foo>')
def foo(foo):
print "here"
data = request.get_json(force=True)
print data
k = data.get('k', 20)
return jsonify(k=k, foo=foostatus='ok')
import requests
params = {'k': 2}
d = requests.get('http://localhost:9090/foo', params=params)
Flask 为请求记录 404。
127.0.0.1 - - [09/Sep/2015 11:26:26] "GET /foo?k=2 HTTP/1.1" 404 -
- 发出带有 JSON 数据的
post
请求,而不是带有查询参数的 get
请求。该路由还需要允许 POST
方法。
- 404 是因为您不打算进行模式匹配
/foo/<foo>
。将默认的路由更改为排除<foo>
,或者转到正确的url.
- 当请求具有正确的 mimetype 时,您不需要将
force=True
与 get_json
一起使用。
- 您的
jsonify
调用中的语法 foo=foostatus='ok'
无效。
- 传递
status
值是多余的,因为 200 响应代码暗示了它。
@app.route('/hello', defautls={'name': 'world'}, methods=['POST'])
@app.route('/hello/<name>', methods=['POST'])
def hello(name):
print(name) # will be 'world' when going to bare /foo
data = request.get_json()
k = data.get('k', 20)
return jsonify(k=k, status='ok')
requests.post('http://localhost/hello', json={'k': 2})
我想使用 Requests post JSON 数据到 Flask 视图。但是,当我发出请求时,我得到了 404。为什么我的代码不起作用?我如何正确postJSON数据?
@app.route('/foo/<foo>', defaults={'foo': 'foo'})
@app.route('/foo/<foo>')
def foo(foo):
print "here"
data = request.get_json(force=True)
print data
k = data.get('k', 20)
return jsonify(k=k, foo=foostatus='ok')
import requests
params = {'k': 2}
d = requests.get('http://localhost:9090/foo', params=params)
Flask 为请求记录 404。
127.0.0.1 - - [09/Sep/2015 11:26:26] "GET /foo?k=2 HTTP/1.1" 404 -
- 发出带有 JSON 数据的
post
请求,而不是带有查询参数的get
请求。该路由还需要允许POST
方法。 - 404 是因为您不打算进行模式匹配
/foo/<foo>
。将默认的路由更改为排除<foo>
,或者转到正确的url. - 当请求具有正确的 mimetype 时,您不需要将
force=True
与get_json
一起使用。 - 您的
jsonify
调用中的语法foo=foostatus='ok'
无效。 - 传递
status
值是多余的,因为 200 响应代码暗示了它。
@app.route('/hello', defautls={'name': 'world'}, methods=['POST'])
@app.route('/hello/<name>', methods=['POST'])
def hello(name):
print(name) # will be 'world' when going to bare /foo
data = request.get_json()
k = data.get('k', 20)
return jsonify(k=k, status='ok')
requests.post('http://localhost/hello', json={'k': 2})