简体   繁体   English

是否可以在 Flask 中发出 POST 请求?

[英]Is it possible to make POST request in Flask?

There is a need to make POST request from server side in Flask.需要在 Flask 中从服务器端发出 POST 请求。

Let's imagine that we have:假设我们有:

@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" })

I haven't found anything specific in Flask documentation.我在 Flask 文档中没有找到任何具体的内容。 Some say urllib2.urlopen is the issue but I failed to combine Flask and urlopen .有人说urllib2.urlopen是问题,但我没有将 Flask 和urlopen结合起来。 Is it really possible?真的有可能吗?

For the record, here's general code to make a POST request from Python:作为记录,以下是从 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()

Notice that we are passing in a Python dict using the json= option.请注意,我们使用json=选项传入 Python 字典。 This conveniently tells the requests library to do two things:这很方便地告诉请求库做两件事:

  1. serialize the dict to JSON将 dict 序列化为 JSON
  2. write the correct MIME type ('application/json') in the HTTP header在 HTTP 标头中写入正确的 MIME 类型 ('application/json')

And here's a Flask application that will receive and respond to that POST request:这是一个 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)

Yes, to make a POST request you can use urllib , see the documentation .是的,要发出 POST 请求,您可以使用urllib ,请参阅文档

I would however recommend to use the requests module instead.但是,我建议改用requests模块。

EDIT :编辑

I suggest you refactor your code to extract the common functionality:我建议您重构代码以提取通用功能:

@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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM