Guest User

Untitled

a guest
Nov 20th, 2017
708
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.24 KB | None | 0 0
  1. #+-------------------------------------------------------------------+
  2. #| *** Exercises - Basic Mapping *** |
  3. #+-------------------------------------------------------------------+
  4. #| |
  5. #| 1. Create a class/mapping for this table, call the class Network |
  6. #| |
  7. #| CREATE TABLE network ( |
  8. #| network_id INTEGER PRIMARY KEY, |
  9. #| name VARCHAR(100) NOT NULL, |
  10. #| ) |
  11. #| |
  12. #| 2. emit Base.metadata.create_all(engine) to create the table |
  13. #| |
  14. #| 3. commit a few Network objects to the database: |
  15. #| |
  16. #| Network(name='net1'), Network(name='net2') |
  17. #+------------------------------------------------------ (25 / 72) --+
  18.  
  19. from sqlalchemy import create_engine
  20. from sqlalchemy import MetaData
  21. from sqlalchemy import Column, Integer, String, Numeric, func,ForeignKey
  22. from sqlalchemy.ext.declarative import declarative_base
  23. from sqlalchemy.orm import Session,relationship
  24. import os
  25.  
  26. metadata = MetaData()
  27. #для выполнения задания создаём базу данных "some"
  28. engine = create_engine("sqlite:///some.db")
  29.  
  30. Base = declarative_base()
  31.  
  32. class Network(Base):
  33. __tablename__ = 'network'
  34.  
  35. network_id = Column(Integer, primary_key=True)
  36. name = Column(String(100), nullable=False)
  37.  
  38. def __repr__(self):
  39. return "<User(%r, %r)>" % (self.name, self.fullname)
  40.  
  41. Base.metadata.create_all(engine)
  42.  
  43. session = Session(bind=engine)
  44. session.add_all([
  45. Network(name='net1'),
  46. Network(name='net2')
  47. ])
  48. session.commit()
  49.  
  50. #+---------------------------------------------------------------------------+
  51. #| *** Exercises - ORM Querying *** |
  52. #+---------------------------------------------------------------------------+
  53. #| 1. Produce a Query object representing the list of "fullname" values for |
  54. #| all User objects in alphabetical order. |
  55. #| |
  56. #| 2. call .all() on the query to make sure it works! |
  57. #| |
  58. #| 3. build a second Query object from the first that also selects |
  59. #| only User rows with the name "mary" or "ed". |
  60. #| |
  61. #| 4. return only the second row of the Query from #3. |
  62. #+-------------------------------------------------------------- (43 / 72) --+
  63.  
  64. class User(Base):
  65. __tablename__ = 'user'
  66.  
  67. id = Column(Integer, primary_key=True)
  68. name = Column(String)
  69. fullname = Column(String)
  70.  
  71. def __repr__(self):
  72. return "<User(%r, %r)>" % (self.name, self.fullname)
  73.  
  74. Base.metadata.create_all(engine)
  75.  
  76. session.add_all([
  77. User(name='wendy', fullname='Wendy Weathersmith'),
  78. User(name='mary', fullname='Mary Contrary'),
  79. User(name='fred', fullname='Fred Flinstone'),
  80. User(name='ed', fullname='Ed Jones')
  81. ])
  82. session.commit()
  83.  
  84. query = session.query(User.fullname).order_by(User.fullname)
  85. print(query.all())
  86. query = query.filter(User.name.in_(['mary','ed']))
  87. print(query.all())
  88. print(query[1])
  89.  
  90. class Address(Base):
  91. __tablename__ = 'address'
  92.  
  93. id = Column(Integer, primary_key=True)
  94. email_address = Column(String, nullable=False)
  95. user_id = Column(Integer, ForeignKey('user.id'))
  96. user = relationship("User", backref="addresses")
  97.  
  98. def __repr__(self):
  99. return "<Address(%r)>" % self.email_address
  100.  
  101. Base.metadata.create_all(engine)
  102.  
  103. jack = User(name='jack', fullname='Jack Bean')
  104. jack.addresses = [Address(email_address='jack@gmail.com'),
  105. Address(email_address='j25@yahoo.com'),
  106. Address(email_address='jack@hotmail.com')]
  107. session.add(jack)
  108. session.commit()
  109.  
  110. #+----------------------------------------------------------------------------+
  111. #| *** Exercises - Final Exam ! *** |
  112. #+----------------------------------------------------------------------------+
  113. #| 1. Create a class called 'Account', with table "account": |
  114. #| |
  115. #| id = Column(Integer, primary_key=True) |
  116. #| owner = Column(String(50), nullable=False) |
  117. #| balance = Column(Numeric, default=0) |
  118. #| |
  119. #| 2. Create a class "Transaction", with table "transaction": |
  120. #| * Integer primary key |
  121. #| * numeric "amount" column |
  122. #| * Integer "account_id" column with ForeignKey('account.id') |
  123. #| |
  124. #| 3. Add a relationship() on Transaction named "account", which refers |
  125. #| to "Account", and has a backref called "transactions". |
  126. #| |
  127. #| 4. Create a database, create tables, then insert these objects: |
  128. #| |
  129. #| a1 = Account(owner='Jack Jones', balance=5000) |
  130. #| a2 = Account(owner='Ed Rendell', balance=10000) |
  131. #| Transaction(amount=500, account=a1) |
  132. #| Transaction(amount=4500, account=a1) |
  133. #| Transaction(amount=6000, account=a2) |
  134. #| Transaction(amount=4000, account=a2) |
  135. #| |
  136. #| 5. Produce a report that shows: |
  137. #| * account owner |
  138. #| * summation of transaction amounts per account (should match balance) |
  139. #| A column can be summed using func.sum(Transaction.amount) |
  140. #+--------------------------------------------------------------- (72 / 72) --+
  141.  
  142. class Account(Base):
  143. __tablename__ = 'account'
  144.  
  145. id = Column(Integer, primary_key=True)
  146. owner = Column(String(50), nullable=False)
  147. balance = Column(Numeric, default=0)
  148.  
  149. def __repr__(self):
  150. return "<Account(%r, %r)>" % (self.owner, self.balance)
  151.  
  152. class Transaction(Base):
  153. __tablename__ = 'transaction'
  154.  
  155. id = Column(Integer, primary_key=True)
  156. amount = Column(Numeric, default=0)
  157. account_id = Column(Integer, ForeignKey('account.id'))
  158. account = relationship("Account", backref="transactions")
  159.  
  160. def __repr__(self):
  161. return "Transaction: %r" % (self.amount)
  162.  
  163. Base.metadata.create_all(engine)
  164.  
  165. a1=Account(owner = "Jack Jones", balance = 5000)
  166. a2=Account(owner="Ed Rendell", balance=10000)
  167. session.add_all([
  168. a1,
  169. a2,
  170. Transaction(amount=500, account=a1),
  171. Transaction(amount=4500, account=a1),
  172. Transaction(amount=6000, account=a2),
  173. Transaction(amount=4000, account=a2)])
  174.  
  175. session.commit()
  176.  
  177. for account in session.query(Account).all():
  178. print(account.owner)
  179. print(account.balance)
  180. sum = 0
  181. for at in account.transactions:
  182. sum += at.amount
  183. print(sum)
  184.  
  185. #+------------------------------------------------------------------+
  186. #| *** Exercises *** |
  187. #+------------------------------------------------------------------+
  188. #| 1. Run this SQL JOIN: |
  189. #| |
  190. #| SELECT user.name, address.email_address FROM user |
  191. #| JOIN address ON user.id=address.user_id WHERE |
  192. #| address.email_address='j25@yahoo.com' |
  193. #| |
  194. #| 2. Tricky Bonus! Select all pairs of distinct user names. |
  195. #| Hint: "... ON user_alias1.name < user_alias2.name" |
  196. #+----------------------------------------------------- (62 / 72) --+
  197.  
  198. query = session.query(User.name, Address.email_address).join(Address).filter(Address.email_address=="j25@yahoo.com")
  199. print(query)
  200. print (query.all())
  201.  
  202. from sqlalchemy.orm import aliased
  203.  
  204. user_alias1 = aliased(User)
  205. user_alias2 = aliased(User)
  206.  
  207. from sqlalchemy import select
  208.  
  209. query=engine.execute(select([user_alias1.name, user_alias2.name]).distinct().where(user_alias1.name < user_alias2.name))
  210. print (query.fetchall())
  211.  
  212. session.close()
  213. #после успешного выполнения задания удаляем базу данных, чтобы она не занимала место на диске
  214. os.remove("some.db")
Add Comment
Please, Sign In to add comment