How to use Peewee with Tornado perfectly

1.2k views Asked by At

I'm useing peewee with my tornado webapp,when I read peewee's document,I found:

Adding Request Hooks

When building web-applications, it is very important that you manage your database connections correctly. In this section I will describe how to add hooks to your web app to ensure the database connection is handled properly. These steps will ensure that regardless of whether you’re using a simple SQLite database, or a pool of multiple Postgres connections, peewee will handle the connections correctly.

http://docs.peewee-orm.com/en/latest/peewee/database.html

Insides,it tells how Flask Django Bottle...to use that except the solution for Tornado

I wonder it's a easy way for tornado to solve this problem? Or this doesn't matter at all?

1

There are 1 answers

1
coleifer On BEST ANSWER

The idea there is that you want to open a connection when a request begins, and close it when the request is finished (the response is returned).

To do this it looks like you can subclass RequestHandler:

from tornado.web import RequestHandler

db = SqliteDatabase('my_db.db')

class PeeweeRequestHandler(RequestHandler):
    def prepare(self):
        db.connect()
        return super(PeeweeRequestHandler, self).prepare()

    def on_finish(self):
        if not db.is_closed():
            db.close()
        return super(PeeweeRequestHandler, self).on_finish()