forked from CincyPy/LibraryWebsite
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
59 lines (47 loc) · 1.76 KB
/
database.py
File metadata and controls
59 lines (47 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from sqlalchemy import create_engine, event
from sqlalchemy.engine import Engine
from sqlalchemy.orm import scoped_session, sessionmaker
from config import config
from models import Base
# Enable Foreign Key Support in sqlite
@event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
class Database(object):
"""
An extremely simplified version of Flask-SQLAlchemy
"""
def __init__(self, app=None):
self._session = None
self.engine = None
self.app = None
if app is not None:
self.init_app(app)
@property
def session(self):
# either instantiate class with app or init_app before accessing the session property
if self._session is not None:
return self._session
return self.create_session()
def create_session(self):
uri = self.app.config['SQLALCHEMY_DATABASE_URI']
self.engine = engine = create_engine(uri, convert_unicode=True)
maker = sessionmaker(autocommit=False, autoflush=False, bind=engine)
self._session = scoped_session(maker)
return self._session
def init_app(self, app):
self.app = app
app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite://')
Base.query = self.session.query_property()
@app.teardown_appcontext
def shutdown_session(response_or_exc):
if app.config.get('SQLALCHEMY_COMMIT_ON_TEARDOWN'):
if response_or_exc is None:
self.session.commit()
self.session.remove()
return response_or_exc
def init_db():
import models
Base.metadata.create_all(bind=engine)