45

需要在 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. 真的有可能吗?

4

2 回答 2

71

作为记录,这是从 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 字典。这方便地告诉 requests 库做两件事:

  1. 将字典序列化为 JSON
  2. 在 HTTP 标头中写入正确的 MIME 类型('application/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)
于 2015-09-23T18:41:05.447 回答
31

是的,要发出可以使用的 POST 请求urllib,请参阅文档

但是,我建议改用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
于 2012-04-25T09:44:16.997 回答