There is a need to make POST request from server side in Flask.
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. Some say urllib2.urlopen
is the issue but I failed to combine Flask and urlopen
. Is it really possible?
To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things.
A GET message is send, and the server returns data. POST. Used to send HTML form data to the server. The data received by the POST method is not cached by the server.
To create a POST request in Python, use the requests. post() method. The requests post() method accepts URL. data, json, and args as arguments and sends a POST request to a specified URL.
For the record, here's general code to make a POST request from Python:
#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. This conveniently tells the requests library to do two things:
And here's a Flask application that will receive and respond to that POST request:
#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.
I would however recommend to use the requests module instead.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With