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()
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 .
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.
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.
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 likegunicorn
oruwsgi
. UseWSGIContainer
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()
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