coolpy
coolpy

Reputation: 163

Making Synchronous Flask Asynchronous - Flask Instances

Normally when people talk about "async" or "making Flask async", they refer to situations where Flask is monkey-patched with some async-tool (GEvent, asyncio, etc.)

Considering that Flask is small enough to be "created on the fly", I thought that this model might work:

Incoming HTTP requests -> HTTP server (eg. nginx/apache) -> HTTP-request-queue -> Flask instance (to handle each request)

Without modifying any of your code, doing any monkey-patches, you essentially get your blocking code to be processed in isolation. After some digging, I believe it can be done:

http://flask.pocoo.org/docs/0.11/deploying/wsgi-standalone/#twisted-web][1]

My questions are:

  1. Is using this approach less efficient than writing event-driven code? (eg. using GEvent or Tornado)

  2. What is the model of how [1] is handling the requests? (is it the same as I described above)

  3. Can a race-condition exist? Eg.

    Making 2 calls to a database where last HTTP request (request-2) is processed first (due to async request-processing), causing a conflict for the first HTTP request (request-1)

Upvotes: 0

Views: 2726

Answers (1)

notorious.no
notorious.no

Reputation: 5107

  1. Assuming "this approach" means using synchronous flask and a wisgi server, the efficiency depends in what your app does. If it's a relatively small app and doesn't require too many long running tasks, then something like Gunicron + Flask is an excellent solution. On the other hand if your app has long running tasks, such as sending out lots of requests to an external site or waiting for Celery tasks to return a result, then I'd recommend an event driven approach + a proxy/load balancer. Anything with an unpredictable amount of latency is generally handled better using async.

  2. It's more or less the same as what you described.

  3. Of course it can happen :) it's what makes web development so interesting. Developers must design very carefully so that such conditions are kept to a minimum.

With that being said, my personal preference is Nginx as the HTTP server and load balancer + Tornado/Twisted combination. This setup offers the most flexibility without many sacrifices and a good balance if you want to use synchronous or asynchronous designs. If you like Flask syntax, there's a very good project called klein which combines Twisted and Werkzeug.

Upvotes: 2

Related Questions