I’d like to send a local REST request in a flask app, like this:
from flask import Flask, url_for, request
import requests
app = Flask(__name__)
@app.route("/<name>/hi", methods=["POST"])
def hi_person(name):
form = {"name": name}
return requests.post(url_for("hi", _external=True), data=form)
@app.route("/hi", methods=["POST"])
def hi():
return 'Hi, %s!' % request.form["name"]
Sending curl -X POST http://localhost:5000/john/hi causes the entire flask app to freeze. When I send a kill signal, I get a broken pipe error. Is there a way to prevent flask from freezing here?
Run your flask app under a proper WSGI server capable of handling concurrent requests (perhaps gunicorn or uWSGI) and it’ll work. While developing, enable threads in the Flask-supplied server with:
but note that the Flask server is not recommended for production use. As of Flask 1.0,
threadedis enabled by default, and you’d want to use theflaskcommand on the command line, really, to run your app.What happens is that using requests you are making a second request to your flask app, but since it is still busy processing the first, it won’t respond to this second request until it is done with that first request.
Incidentally, under Python 3 the socketserver implementation handles the disconnect more gracefully and continues to serve rather than crash.