From c57494ae405ffbdd8ec45f74ef04ea85895f1bf7 Mon Sep 17 00:00:00 2001 From: Jon Bergli Heier Date: Fri, 15 Mar 2019 18:45:47 +0100 Subject: Port application to flask --- pastepy/db.py | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 pastepy/db.py (limited to 'pastepy/db.py') diff --git a/pastepy/db.py b/pastepy/db.py new file mode 100644 index 0000000..0aa04a1 --- /dev/null +++ b/pastepy/db.py @@ -0,0 +1,68 @@ +from contextlib import contextmanager + +from flask import current_app +from sqlalchemy import create_engine, Column, Integer, String, DateTime, Text, Index, ForeignKey +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker, relation, backref +from sqlalchemy.orm.exc import NoResultFound + +engine = create_engine(current_app.config['DB_PATH']) + +Base = declarative_base(bind = engine) + +class Paste(Base): + __tablename__ = 'paste' + + id = Column(Integer, primary_key = True) + hash = Column(String, unique = True, index = True) + nick = Column(String) + date = Column(DateTime, nullable = False) + syntax = Column(String) + title = Column(String) + text = Column(Text, nullable = False) + ip = Column(String) + + def __init__(self, hash, nick, date, syntax, title, text, ip=None): + self.nick = nick + self.hash = hash + self.date = date + self.syntax = syntax + self.title = title + self.text = text + self.ip = ip + + def __repr__(self): + return '' % (self.id, self.hash, self.nick, self.date.ctime(), self.title) + +class Cache(Base): + __tablename__ = 'cache' + + id = Column(Integer, primary_key = True) + paste_hash = Column(String, ForeignKey('paste.hash'), index = True) + paste = relation(Paste, primaryjoin = paste_hash == Paste.hash, lazy = False) + syntax_name = Column(String) + text = Column(Text, nullable = False) + + def __init__(self, hash, syntax_name, text): + self.paste_hash = hash + self.syntax_name = syntax_name + self.text = text + + def __repr__(self): + return '' % (self.id, self.paste_hash) + +Base.metadata.create_all() +Session = sessionmaker(bind = engine, autoflush = True, autocommit = False) + +@contextmanager +def session_scope(): + session = Session() + try: + session.expire_on_commit = False + yield session + session.commit() + except: + session.rollback() + raise + finally: + session.close() -- cgit v1.2.3