0

I'm using the Peewee ORM in my Python WSGI web app. I've been having issues with the MySQL Server "going away", so I switched to the PooledMySQLDatabase. I will still having issues with the server going away after a few hours..

According to the Docs, for best performance I must manage the connection(s) myself, by calling .connect() and .close(). I was not doing this at all.

I've added 2 decorators that get called before and after every request, but is this correct?

@pre_save()
def pre_save_handler(sender,instance,created):
    db.connect()
    logger.debug('Attempting to save %s' % instance)

@post_save()
def post_save_handler(sender, instance, created):
    db.close()
    logger.debug('%s was just saved' % instance)

Are there any pitfalls doing it this way? Should I move the .connect() and .close() into my application?

mox1
  • 614
  • 3
  • 10

2 Answers2

1

Most WSGI frameworks provide some sort of hook for running code before and after a request. I suggest using those hooks to connect/close.

Check out these docs: http://docs.peewee-orm.com/en/latest/peewee/database.html#adding-request-hooks

coleifer
  • 24,887
  • 6
  • 60
  • 75
  • Thank you for the doc pointer. I'm actually using http://webpy.org/ , which has hooks -http://webpy.org/cookbook/application_processors . Through my testing it seems that peewee will call .connect() for me if I don't. Is it safe to assume peewee will do this in all situations, or should I explicitly call .connect() AND .close() – mox1 Jan 14 '15 at 17:53
0

After thinking about this for a day or two, I realized this is 100% the wrong way to do it. This won't work at all for SELECT queries. These functions only get called on database stores! I've added a pre and post processor to my web app and it is now functioning correctly.

mox1
  • 614
  • 3
  • 10