Vis*_*ioN 28 python post flask
需要在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" })
Run Code Online (Sandbox Code Playgroud)
我没有在Flask文档中找到任何具体内容.有人说urllib2.urlopen是问题,但我没能把Flask和urlopen.真的有可能吗?
提前致谢!
Luk*_*uke 35
为了记录,这是从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()
Run Code Online (Sandbox Code Playgroud)
请注意,我们使用该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)
Run Code Online (Sandbox Code Playgroud)
cod*_*ape 26
是的,要发出可以使用的POST请求urllib2,请参阅文档.
但是我建议使用请求模块.
编辑:
我建议你重构你的代码来提取常用功能:
@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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53453 次 |
| 最近记录: |