From 1fb9db3f4b391073c590c12d80e4934efa64327d Mon Sep 17 00:00:00 2001 From: Tanner Collin Date: Fri, 26 Jun 2020 00:21:03 +0000 Subject: [PATCH] Store ref list in database too --- apiserver/database.py | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/apiserver/database.py b/apiserver/database.py index dc7fd37..ef31f26 100644 --- a/apiserver/database.py +++ b/apiserver/database.py @@ -1,6 +1,6 @@ import json -from sqlalchemy import create_engine, Column, String +from sqlalchemy import create_engine, Column, String, ForeignKey, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker @@ -12,10 +12,17 @@ Base = declarative_base() class Story(Base): __tablename__ = 'stories' - sid = Column(String, primary_key=True) + sid = Column(String(16), primary_key=True) meta_json = Column(String) full_json = Column(String) +class Reflist(Base): + __tablename__ = 'reflist' + + rid = Column(Integer, primary_key=True) + ref = Column(String(16), unique=True) + sid = Column(String, ForeignKey('stories.sid'), unique=True) + def init(): Base.metadata.create_all(engine) @@ -27,7 +34,7 @@ def get_full(sid): session = Session() return session.query(Story).get(sid).full_json -def put(story): +def put_story(story): full_json = json.dumps(story) story.pop('text') @@ -44,3 +51,23 @@ def put(story): raise finally: session.close() + +def get_reflist(amount): + session = Session() + q = session.query(Reflist).order_by(Reflist.rid.desc()).limit(amount) + return [dict(ref=x.ref, sid=x.sid) for x in q.all()] + +def put_ref(ref, sid): + try: + session = Session() + r = Reflist(ref=ref, sid=sid) + session.add(r) + session.commit() + except: + session.rollback() + raise + finally: + session.close() + +if __name__ == '__main__': + init()