Guest User

Untitled

a guest
Jun 23rd, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.19 KB | None | 0 0
  1. import os
  2. import sys
  3. from sqlalchemy import Column, ForeignKey, Integer, String
  4. from sqlalchemy.ext.declarative import declarative_base
  5. from sqlalchemy.orm import relationship
  6. from sqlalchemy import create_engine
  7. import sqlalchemy_utils
  8.  
  9. #Drop DB if it exists.
  10. if sqlalchemy_utils.database_exists('postgresql:///bankapi.db'):
  11. sqlalchemy_utils.drop_database('postgresql:///bankapi.db')
  12. sqlalchemy_utils.create_database('postgresql:///bankapi.db')
  13.  
  14. Base = declarative_base()
  15.  
  16. #DB Models.
  17. class UserWallet(Base):
  18. __tablename__ = 'wallet'
  19.  
  20. uid = Column(Integer, primary_key=True, autoincrement=True)
  21. funds = Column(Integer, nullable=True)
  22.  
  23. @property
  24. def serialize(self):
  25. return {
  26. 'uid' : uid,
  27. 'funds' : funds,
  28. }
  29.  
  30. class Account(Base):
  31. __tablename__ = 'accounts'
  32.  
  33. aid = Column(Integer, primary_key=True, autoincrement=True)
  34. name = Column(String(50), nullable=False)
  35. hodlings = Column(Integer, nullable=True)
  36.  
  37. @property
  38. def serialize(self):
  39. return {
  40. 'aid' : self.aid,
  41. 'name' : self.name,
  42. 'hodlings' : self.hodlings,
  43. }
  44.  
  45. class Transaction(Base):
  46. __tablename__ = 'transactions'
  47.  
  48. txid = Column(Integer, primary_key=True, autoincrement=True)
  49. aid = Column(Integer, ForeignKey('accounts.aid'))
  50. amount = Column(Integer, nullable=False)
  51. account = relationship(Account)
  52.  
  53. @property
  54. def serialize(self):
  55. return {
  56. 'txid' : self.txid,
  57. 'aid' : self.aid,
  58. 'amount' : self.amount,
  59. }
  60.  
  61. #DB Engine.
  62. engine = create_engine('postgresql:///bankapi.db')
  63. Base.metadata.create_all(engine)
  64.  
  65. from database_template import Base, Account, Transaction, UserWallet
  66. import sqlalchemy
  67. import flask
  68. import random
  69. import string
  70. import httplib2
  71. import json
  72. import sqlalchemy_utils
  73.  
  74. #Initiate Flask Server
  75. app = flask.Flask(__name__)
  76.  
  77. #Initiate DB Engine.
  78. engine = sqlalchemy.create_engine('postgresql:///bankapi.db')
  79. Base.metadata.bind = engine
  80. dbsession = sqlalchemy.orm.sessionmaker(bind=engine)
  81. session = dbsession()
  82.  
  83. #API reset.
  84. @app.route('/reset')
  85. def api_reset():
  86. meta = Base.metadata
  87. for table in reversed(meta.sorted_tables):
  88. session.execute(table.delete())
  89. session.commit()
  90. return 'Database Reset, return to / or /accounts' + 'n'
  91.  
  92. #Root / Show all accounts.
  93. @app.route('/')
  94. @app.route('/accounts')
  95. def accounts_all():
  96. user = session.query(UserWallet).all()
  97. if user:
  98. accounts = session.query(Account).all()
  99. if accounts:
  100. u = 'Current Wallet: ' + str(user[0].funds) + 'n'
  101. x = 'Your accounts are listed below:' +'n'
  102. y = 'n'.join(str(a.aid) for a in accounts)
  103. z = 'n''To create a new account, make a POST request to /accounts/new_ac'
  104. zz = 'n' + 'arguments for [name] are required.' + 'n'
  105. return u + x + y + z + zz
  106. else:
  107. return 'There are no accounts, curl to make some' + 'n'
  108. else:
  109. newUser = UserWallet(funds=1000000)
  110. session.add(newUser)
  111. session.commit()
  112. return 'Welcome, your initial personal wallet balance is 1000000sat.' +
  113. 'n' + 'Follow the curl guide included in the respository to manage' +
  114. 'n' + 'your accounts. Have fun and rest assured, funds are safe.' + 'n'
  115.  
  116.  
  117. #Create New Account.
  118. @app.route('/accounts/new_ac', methods=['GET','POST'])
  119. def account_new():
  120. if flask.request.method == 'POST':
  121. data = flask.request.get_json()
  122. if data['name']:
  123. aname = data['name']
  124. newAccount = Account(name=aname, hodlings=0)
  125. session.add(newAccount)
  126. session.commit()
  127. return '{} Account Successfully Created'.format(newAccount.name) + 'n'
  128. else:
  129. return 'Arguments [name, password] are required.' + 'n'
  130. else:
  131. return 'Accounts can only be created via POST requests.' + 'n'
  132.  
  133. #Create New Transaction.
  134. @app.route('/accounts/<int:account_id>/tx/new', methods=['GET','POST'])
  135. def tx_new(account_id):
  136. try:
  137. active_ac = session.query(Account).filter_by(aid=account_id).one()
  138. except:
  139. return 'Invalid Account ID.' + 'n'
  140. if flask.request.method == 'POST':
  141. data = flask.request.get_json()
  142. if data['amount']:
  143. tx_amount = data['amount']
  144. check_bal = active_ac.hodlings + tx_amount
  145. userwal = session.query(UserWallet).one()
  146. check_wal = userwal.funds - tx_amount
  147. if check_bal < 0:
  148. return 'Not enough hodlings for specified withdrawal.' + 'n'
  149. elif check_wal < 0:
  150. return 'Not enough funds for specified deposit.' + 'n'
  151. new_tx = Transaction(aid=account_id, amount=tx_amount)
  152. session.add(new_tx)
  153. active_ac.hodlings += tx_amount
  154. userwal.funds -= tx_amount
  155. session.commit()
  156. latest_tx = session.query(Transaction).order_by(Transaction.txid.desc()).first()
  157. latest_txid = latest_tx.txid
  158. return 'Tx {} succesfully created'.format(latest_txid) + 'n'
  159. else:
  160. return 'Arguments [amount,password] are required.' + 'n'
  161. else:
  162. return 'Transactions can only be created via POST requests.' + 'n'
  163.  
  164. #API Serialized Data Endpoints.
  165. @app.route('/accounts/<int:account_id>/JSON')
  166. def account_page(account_id):
  167. try:
  168. active_ac = session.query(Account).filter_by(aid=account_id).one()
  169. except:
  170. return 'Invalid Account ID.' + 'n'
  171. return flask.jsonify(Account=active_ac.serialize)
  172.  
  173. @app.route('/accounts/<int:account_id>/tx/JSON')
  174. def tx_all(account_id):
  175. try:
  176. active_tx = session.query(Transaction).filter_by(aid=account_id).all()
  177. except:
  178. return 'Invalid Account ID.' + 'n'
  179. if active_tx:
  180. return flask.jsonify(Transaction=[tx.serialize for tx in active_tx])
  181. else:
  182. return 'No transactions to display' + 'n'
  183.  
  184. @app.route('/accounts/<int:account_id>/tx/<int:tx_id>/JSON')
  185. def tx_page(account_id, tx_id):
  186. try:
  187. tx = session.query(Transaction).filter_by(txid=tx_id, aid=account_id).one()
  188. except:
  189. return 'One of the specified IDs is not valid.' + 'n'
  190. return flask.jsonify(Transaction=tx.serialize)
  191.  
  192.  
  193. if __name__ == '__Main__':
  194. app.run()
Add Comment
Please, Sign In to add comment