Open and close the db connection at the beginning and end of each request.
This commit is contained in:
parent
f572749ace
commit
39018e72f1
1 changed files with 17 additions and 0 deletions
|
@ -1,4 +1,5 @@
|
||||||
import string
|
import string
|
||||||
|
import logging
|
||||||
|
|
||||||
from random import SystemRandom
|
from random import SystemRandom
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
@ -8,10 +9,26 @@ from peewee import create_model_tables
|
||||||
from app import app
|
from app import app
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
db = app.config['DB_DRIVER'](app.config['DB_NAME'],
|
db = app.config['DB_DRIVER'](app.config['DB_NAME'],
|
||||||
**app.config['DB_CONNECTION_ARGS'])
|
**app.config['DB_CONNECTION_ARGS'])
|
||||||
|
|
||||||
|
|
||||||
|
def connect_db():
|
||||||
|
logger.debug('Connectin to database.')
|
||||||
|
db.connect()
|
||||||
|
|
||||||
|
|
||||||
|
def close_db(exc):
|
||||||
|
if not db.is_closed():
|
||||||
|
logger.debug('Disconnecting from database.')
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
app.before_request(connect_db)
|
||||||
|
app.teardown_request(close_db)
|
||||||
|
|
||||||
|
|
||||||
class BaseModel(Model):
|
class BaseModel(Model):
|
||||||
class Meta:
|
class Meta:
|
||||||
database = db
|
database = db
|
||||||
|
|
Reference in a new issue