需要在 Flask 中从服务器端发出 POST 请求。
让我们想象一下,我们有:
@app.route("/test", methods=["POST"])
def test():
test = request.form["test"]
return "TEST: %s" % test
@app.route("/index")
def index():
# Is there something_like_this method in Flask to perform the POST request?
return something_like_this("/test", { "test" : "My Test Data" })
我在 Flask 文档中没有找到任何具体内容。有人说urllib2.urlopen
是问题所在,但我未能将Flask和urlopen
结合起来。真的可能吗?
作为记录,以下是从 Python 发出 POST 请求的一般代码:
#make a POST request
import requests
dictToSend = {'question':'what is the answer?'}
res = requests.post('http://localhost:5000/tests/endpoint', json=dictToSend)
print 'response from server:',res.text
dictFromServer = res.json()
请注意,我们使用 json=
选项传入 Python 字典。这方便地告诉请求库做两件事:
- 将字典序列化为 JSON
- 在 HTTP 标头中写入正确的 MIME 类型("应用程序/json")
下面是一个 Flask 应用程序,它将接收并响应该 POST 请求:
#handle a POST request
from flask import Flask, render_template, request, url_for, jsonify
app = Flask(__name__)
@app.route('/tests/endpoint', methods=['POST'])
def my_test_endpoint():
input_json = request.get_json(force=True)
# force=True, above, is necessary if another developer
# forgot to set the MIME type to 'application/json'
print 'data from client:', input_json
dictToReturn = {'answer':42}
return jsonify(dictToReturn)
if __name__ == '__main__':
app.run(debug=True)
是的,要发出 POST 请求,您可以使用 urllib
,请参阅文档。
但是,我建议改用请求模块。
编辑:
我建议你重构你的代码来提取通用功能:
@app.route("/test", methods=["POST"])
def test():
return _test(request.form["test"])
@app.route("/index")
def index():
return _test("My Test Data")
def _test(argument):
return "TEST: %s" % argument