需要在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
结合起来。真的有可能吗?
提前致谢!
答案 0 :(得分:27)
对于记录,这是从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 dict。这方便地告诉请求库做两件事:
这是一个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)
答案 1 :(得分:26)
是的,要发出POST请求,您可以使用urllib2
,请参阅documentation。
但我建议改为使用requests模块。
修改强>:
我建议您重构代码以提取常用功能:
@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