Add database bits.

This commit is contained in:
Edward Betts 2019-09-25 13:22:42 +01:00
parent 43a3cd566c
commit 2a403cb544
2 changed files with 56 additions and 0 deletions

21
depicts/database.py Normal file
View file

@ -0,0 +1,21 @@
from sqlalchemy import create_engine, func
from sqlalchemy.orm import scoped_session, sessionmaker
session = scoped_session(sessionmaker())
def init_db(db_url):
session.configure(bind=get_engine(db_url))
def get_engine(db_url):
return create_engine(db_url, pool_recycle=3600, pool_size=20, max_overflow=40)
def init_app(app, echo=False):
db_url = app.config['DB_URL']
session.configure(bind=get_engine(db_url, echo=echo))
@app.teardown_appcontext
def shutdown_session(exception=None):
session.remove()
def now_utc():
return func.timezone('utc', func.now())

35
depicts/model.py Normal file
View file

@ -0,0 +1,35 @@
from sqlalchemy.ext.declarative import declarative_base
from .database import session
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import Integer, String
from sqlalchemy.orm import column_property, relationship
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.sql.expression import cast
Base = declarative_base()
Base.query = session.query_property()
class DepictsItem(Base):
__tablename__ = 'depicts'
item_id = Column(Integer, primary_key=True, autoincrement=False)
label = Column(String)
description = Column(String)
commons = Column(String)
count = Column(Integer)
qid = column_property('Q' + cast(item_id, String))
db_alt_labels = relationship('DepictsItemAltLabel',
collection_class=set,
cascade='save-update, merge, delete, delete-orphan',
backref='item')
alt_labels = association_proxy('db_alt_labels', 'alt_label')
class DepictsItemAltLabel(Base):
__tablename__ = 'depicts_alt_label'
item_id = Column(Integer,
ForeignKey('depicts.item_id'),
primary_key=True,
autoincrement=False)
alt_label = Column(String, primary_key=True)
def __init__(self, alt_label):
self.alt_label = alt_label