简体   繁体   中英

How to use Peewee with Tornado perfectly

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM