using Flask and Tornado together?

Abdelouahab picture Abdelouahab · Nov 15, 2011 · Viewed 39.2k times · Source

I am a big fan of Flask - in part because it is simple and in part because has a lot of extensions. However, Flask is meant to be used in a WSGI environment, and WSGI is not a non-blocking, so (I believe) it doesn't scale as well as Tornado for certain kinds of applications.

Since each one has an URL dispatcher which will call a function, and both will use Python files (in Django you dont launch the python file but in flask or tornado you do) do does it make sense to have two seperate parts to your website - one part running the non-blocking jobs with Tornado, and the other part written with Flask?

If this is a good idea, how would you go about sharing cookies / sessions between Flask and Tornado? Will I run into issues, since Flask will use it own system and Tornado will use its own system?

Answer

Abdelouahab picture Abdelouahab · Nov 23, 2011

i think i got 50% of the solution, the cookies are not tested yet, but now i can load Flask application using Tornado, and mixing Tornado + Flask together :)

first here is flasky.py the file where the flask application is:

from flask import Flask
app = Flask(__name__)

@app.route('/flask')
def hello_world():
  return 'This comes from Flask ^_^'

and then the cyclone.py the file which will load the flask application and the tornado server + a simple tornado application, hope there is no module called "cyclone" ^_^

from tornado.wsgi import WSGIContainer
from tornado.ioloop import IOLoop
from tornado.web import FallbackHandler, RequestHandler, Application
from flasky import app

class MainHandler(RequestHandler):
  def get(self):
    self.write("This message comes from Tornado ^_^")

tr = WSGIContainer(app)

application = Application([
(r"/tornado", MainHandler),
(r".*", FallbackHandler, dict(fallback=tr)),
])

if __name__ == "__main__":
  application.listen(8000)
  IOLoop.instance().start()

hope this will help someone that wants to mix them :)