Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Flask app with Tornado

I would like to run a simple app written in Flask with Tornado. How do I do this? I want to use Python 2.7 and the latest Tornado version (4.2).

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()
like image 463
guagay_wk Avatar asked May 31 '15 23:05

guagay_wk


People also ask

How do I run an app with a Flask?

To run the app outside of the VS Code debugger, use the following steps from a terminal: Set an environment variable for FLASK_APP . On Linux and macOS, use export set FLASK_APP=webapp ; on Windows use set FLASK_APP=webapp . Navigate into the hello_app folder, then launch the program using python -m flask run .

Can you run Flask on Apache?

Flask is a fantastic micro web framework for Python, however, it is not a native web language. So to get our Python code running on a web server is tricky. Apache will use WSGI file to access our Flask application, so the WSGI file allows Apache to interact with Python as if it is native. It's a simple script.

Can Flask run multiple threads?

As of Flask 1.0, flask server is multi-threaded by default. Each new request is handled in a new thread. This is a simple Flask application using default settings.


1 Answers

The Flask docs used to describe how to do this, but it has been removed due to the performance notes below. You don't need Tornado to serve your Flask app, unless all your async code is already written in Tornado.

The Tornado docs about WSGI describe this as well. They also include a big warning that this is probably less performant than using a dedicated WSGI app server such as uWSGI, Gunicorn, or mod_wsgi.

WSGI is a synchronous interface, while Tornado’s concurrency model is based on single-threaded asynchronous execution. This means that running a WSGI app with Tornado’s WSGIContainer is less scalable than running the same app in a multi-threaded WSGI server like gunicorn or uwsgi. Use WSGIContainer only when there are benefits to combining Tornado and WSGI in the same process that outweigh the reduced scalability.

For example, use Gunicorn instead:

gunicorn -w 4 app:app

After all that, if you really, really still want to use Tornado, you can use the pattern described in the docs:

from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from yourapplication import app

http_server = HTTPServer(WSGIContainer(app))
http_server.listen(5000)
IOLoop.instance().start()
like image 117
davidism Avatar answered Oct 19 '22 23:10

davidism