daily pastebin goal
77%
SHARE
TWEET

Untitled

namelesszot Mar 17th, 2018 34 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #! /usr/bin/ python3
  2.  
  3. from sqlalchemy.ext.declarative import declarative_base
  4. from sqlalchemy.orm import sessionmaker, relationship
  5. from sqlalchemy import Column, Integer, Unicode, UniqueConstraint, ForeignKey, DateTime, create_engine
  6.  
  7. CBase = declarative_base()
  8.  
  9.  
  10. class User(CBase):
  11.  
  12.     __tablename__ = 'users'
  13.  
  14.     id = Column(Integer(), primary_key=True)
  15.     username = Column(Unicode())
  16.     password = Column(Unicode())
  17.     information = Column(Unicode())
  18.  
  19.     unique_username = UniqueConstraint('username')
  20.  
  21.     messages_to = relationship('Message', backref='users', foreign_keys='Message.user_to_id', lazy='dynamic')
  22.     messages_from = relationship('Message', backref='users', foreign_keys='Message.user_from_id', lazy='dynamic')
  23.  
  24.     def __repr__(self):
  25.         return 'Users<id = %s, username = %s, messages=%s' % (self.id, self.username, self.messages)
  26.  
  27.  
  28. class Message(CBase):
  29.  
  30.     __tablename__ = 'messages'
  31.  
  32.     id = Column(Integer(), primary_key=True)
  33.     user_from_id = Column(Integer(), ForeignKey('users.id'))
  34.     user_to_id = Column(Integer(), ForeignKey('users.id'))
  35.     message = Column(Unicode())
  36.     datetime = Column(DateTime())
  37.  
  38.     user_from = relationship('User', backref='messages', foreign_keys=user_from_id)
  39.     user_to = relationship('User', backref='messages', foreign_keys=user_to_id)
  40.  
  41.     def __repr__(self):
  42.         return 'Messages: id=%s, user_from=%s, user_to=%s, message="%s"' % \
  43.                (self.id, self.user_from_id, self.user_to_id, self.message)
  44.  
  45. engine = create_engine('mysql+pymysql://root:root@localhost:3306/server_db')
  46. session = sessionmaker(bind=engine)()
  47.  
  48. msgs = session.query(User).all()
  49. for msg in msgs:
  50.     print(msg)
  51.  
  52. msgs = session.query(Message).all()
  53. for msg in msgs:
  54.     print(msg)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top