db.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from aiopg.sa import create_engine as async_engine
  2. from sqlalchemy import ForeignKey, CheckConstraint
  3. from sqlalchemy import create_engine
  4. from sqlalchemy import Column, Integer, String, Text, DECIMAL, Boolean, exc, event, MetaData, select, DateTime
  5. from sqlalchemy import desc
  6. from sqlalchemy import func
  7. from sqlalchemy.sql.expression import true, false
  8. from sqlalchemy.engine.url import URL
  9. from sqlalchemy.orm import sessionmaker, relationship, backref
  10. from sqlalchemy.ext.associationproxy import association_proxy
  11. from sqlalchemy.ext.declarative import declarative_base, as_declarative, declared_attr
  12. import json
  13. DATABASE = {
  14. 'drivername': 'postgres',
  15. 'host': '127.0.0.1',
  16. 'port': '5432',
  17. 'username': 'xmasdamin',
  18. 'password': 'xmasadmin',
  19. 'database': 'xmasdb'
  20. }
  21. Base = declarative_base()
  22. metadata = MetaData()
  23. engine = create_engine(URL(**DATABASE))
  24. Session = sessionmaker(bind=engine)
  25. session = Session()
  26. class Attendee(Base):
  27. __tablename__ = 'attendee'
  28. id = Column(Integer, primary_key=True)
  29. name = Column(String)
  30. guest = Column(Boolean)
  31. cat = Column(String)
  32. def serialize(self):
  33. return {
  34. 'id': self.id,
  35. 'name': self.name,
  36. 'cat': self.cat,
  37. 'guest': str(self.guest)
  38. }
  39. async def add_attendee(name, guest, cat):
  40. attendee = session.query(Attendee).filter(Attendee.name == name).first()
  41. if attendee is None:
  42. attendee = Attendee(name=name, guest=guest, cat=cat)
  43. else:
  44. attendee.name = name
  45. attendee.guest = guest
  46. attendee.cat = cat
  47. if attendee is not None:
  48. session.add(attendee)
  49. session.commit()
  50. return True
  51. else:
  52. return False
  53. async def fetch_attendees():
  54. attendees = session.query(Attendee).all()
  55. if attendees is not None:
  56. return attendees
  57. else:
  58. return False