Answer the question
In order to leave comments, you need to log in
How to make parallel requests in Flask rest api?
I don't really know how to make parallel requests to a REST API (in Flask) in python and avoid the problem of concurrent requests.
I take flask.pocoo.org/docs/0.10/quickstart and build a simple flow:
from flask import Flask, jsonify, make_response, abort,request
import time
app = Flask(__name__)
tasks = [
{
'id': 1,
'title': u'Buy groceries',
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': False
},
{
'id': 2,
'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the web',
'done': False
}
]
@app.route("/")
def hello():
time.sleep(100)
return "Hello World!"
@app.route('/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
@app.route('/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
task = filter(lambda t: t['id'] == task_id, tasks)
if len(task) == 0:
abort(404)
if task_id==2:
print "sleeping..."
time.sleep(1000)
return jsonify({'task': task[0]})
@app.route('/tasks', methods=['POST'])
def create_task():
if not request.json or not 'title' in request.json:
abort(400)
task = {
'id': tasks[-1]['id'] + 1,
'title': request.json['title'],
'description': request.json.get('description', ""),
'done': False
}
tasks.append(task)
return jsonify({'task': task}), 201
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
if __name__ == "__main__":
app.debug = True
app.run(host='0.0.0.0',port=8888)
@app.route('/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
task = filter(lambda t: t['id'] == task_id, tasks)
if len(task) == 0:
abort(404)
if task_id==2:
print "sleeping..."
time.sleep(1000)
return jsonify({'task': task[0]})
* Running on http://0.0.0.0:8888/
* Restarting with reloader
127.0.0.1 - - [21/Jan/2015 14:06:47] "GET /tasks/3 HTTP/1.1" 404 -
127.0.0.1 - - [21/Jan/2015 14:06:51] "GET /tasks/1 HTTP/1.1" 200 -
sleeping...
Answer the question
In order to leave comments, you need to log in
You are running the web server in single threaded mode. Until one request completes, another will not pass. You need to configure gunicorn+nginx , for example. There are other options.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question