作为记录,这是从 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 库做两件事:
- 将字典序列化为 JSON
- 在 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)