app.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. from flask import Flask, abort, jsonify, url_for, render_template, g, request
  2. from flask.json import JSONEncoder
  3. from flask_sqlalchemy import SQLAlchemy
  4. from flask_httpauth import HTTPBasicAuth
  5. import decimal, re, json
  6. from passlib.apps import custom_app_context as pwd_context
  7. from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired)
  8. app = Flask(__name__)
  9. #Configuration for Database ORM
  10. app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://groceryadmin:VKov2q3XTtqj6w9o@localhost/groceryapp'
  11. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
  12. db = SQLAlchemy(app)
  13. app.config['SECRET_KEY'] = 'geunyeorang cheoeum daehoa sijag hajamaja'
  14. auth = HTTPBasicAuth()
  15. #This helper class will be used to facilitate the printing of database objects as strings
  16. # class MJSONEncoder(JSONEncoder):
  17. # def default(self, obj):
  18. # if isinstance(obj, decimal.Decimal):
  19. # # Convert decimal instances to strings.
  20. # return str(obj)
  21. # return super(MJSONEncoder, self).default(obj)
  22. #
  23. #
  24. # app.json_encoder = MJSONEncoder
  25. class User(db.Model):
  26. __tablename__ = "users"
  27. id = db.Column(db.Integer, primary_key=True)
  28. email = db.Column(db.String(120), unique=True)
  29. password_hash = db.Column(db.String(128))
  30. def hash_password(self, password):
  31. self.password_hash = pwd_context.encrypt(password)
  32. print(self.password_hash)
  33. def verify_password(self, password):
  34. return pwd_context.verify(password, self.password_hash)
  35. def generate_auth_token(self, expiration=600):
  36. s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
  37. return s.dumps({'id': self.id})
  38. @staticmethod
  39. def verify_auth_token(token):
  40. print ('48 - ' + token)
  41. s = Serializer(app.config['SECRET_KEY'])
  42. try:
  43. data = s.loads(token)
  44. except SignatureExpired:
  45. return None # valid token, but expired
  46. except BadSignature:
  47. return None # invalid token
  48. user = User.query.get(data['id'])
  49. if user is None:
  50. return
  51. return user
  52. @auth.verify_password
  53. def verify_password(email_or_token, password):
  54. # first try to authenticate by token
  55. user = User.verify_auth_token(email_or_token)
  56. if not user:
  57. # try to authenticate with username/password
  58. user = User.query.filter_by(email=email_or_token).first()
  59. print ('86')
  60. print (user)
  61. if not user or not user.verify_password(password):
  62. return False
  63. g.user = user
  64. return True
  65. @app.route('/', methods = ['GET', 'POST'])
  66. def index():
  67. if request.method == 'POST':
  68. if request.form['submit'] == 'calculate_btn':
  69. weight1 = request.form['weight1']
  70. weight2 = request.form['weight2']
  71. print (weight1)
  72. print (weight2)
  73. # my_total = calculate(weight1, weight2)
  74. # print (my_total)
  75. my_total = 69
  76. return my_total
  77. if request.method == 'GET':
  78. return render_template('index.html')
  79. @app.route('/calculate_total/', methods = ['GET'])
  80. def calculate():
  81. print (request)
  82. print (request.view_args)
  83. item1 = (request.args.get('item1'))
  84. item2 = (request.args.get('item2'))
  85. price1 = (request.args.get('price1'))
  86. price2 = (request.args.get('price2'))
  87. weight1 = (request.args.get('weight1'))
  88. weight2 = (request.args.get('weight2'))
  89. # total2 = float(total)
  90. # new_total = 1.0 + total2
  91. # print(new_total)
  92. item1_byWeight = float(price1) / float(weight1);
  93. item2_byWeight = float(price2) / float(weight2);
  94. if (item1_byWeight < item2_byWeight) :
  95. difference = float(item2_byWeight) - float(item1_byWeight)
  96. result = (item1 + "is cheapter by " + difference)
  97. else :
  98. difference = float(item1_byWeight) - float(item2_byWeight)
  99. result = (item2 + "is cheapter by " + difference)
  100. print(result)
  101. return result
  102. def calculate(weight1, weight2):
  103. total = weight1 + weight2
  104. return total
  105. @app.route('/login', methods=['POST'])
  106. def login():
  107. if request.headers['content-Type'] == 'application/x-www-form-urlencoded':
  108. email = request.form['email']
  109. password = request.form['password']
  110. if email is None or password is None:
  111. abort(400)
  112. if User.query.filter_by(email=email).first() is not None:
  113. verify = verify_password(email, password)
  114. user = User(email=email)
  115. print('108 - ' + verify)
  116. if verify:
  117. print('You already in there\n')
  118. return render_template('success.html')
  119. else:
  120. print ('Login failed')
  121. return 'Login failed'
  122. user = User(email=email)
  123. User.hash_password(user, password)
  124. db.session.add(user)
  125. db.session.commit()
  126. return render_template('success.html')
  127. elif request.headers['Content-Type'] == 'application/json':
  128. print ('122')
  129. print(request.json)
  130. email = request.json.get('email')
  131. password = request.json.get('password')
  132. if email is None or password is None:
  133. abort(400)
  134. if User.query.filter_by(email=email).first() is not None:
  135. verify = verify_password(email, password)
  136. user = User(email=email)
  137. print ('130')
  138. print (verify)
  139. if verify:
  140. print (g.user.id)
  141. token = g.user.generate_auth_token(600)
  142. return jsonify({'email': user.email, 'authToken': token.decode('ascii')}), 201, {
  143. 'Location': url_for('get_user', id=g.user.id, _external=True)}
  144. else:
  145. print ('Error: Login Unsuccessful')
  146. return 'Error: Login Unsuccessful'
  147. user = User(email=email)
  148. User.hash_password(user, password)
  149. db.session.add(user)
  150. db.session.commit()
  151. verify_password(email, password)
  152. token = g.user.generate_auth_token(600)
  153. return jsonify({'email': user.email, 'authToken': token.decode('ascii')}), 201, {'Location': url_for('get_user', id=user.id, _external=True)}
  154. @app.route('/users/<int:id>')
  155. @auth.login_required
  156. def get_user(id):
  157. user = User.query.get(id)
  158. if not user:
  159. abort(400)
  160. return jsonify({'email': user.email, 'password': user.password_hash})
  161. @app.route('/token')
  162. @auth.login_required
  163. def get_auth_token():
  164. token = g.user.generate_auth_token(600)
  165. return jsonify({'token': token.decode('ascii'), 'duration': 600})
  166. @app.route('/resource')
  167. @auth.login_required
  168. def get_resource():
  169. return jsonify({'data': 'Hello, %s!' % g.user.email})
  170. if __name__ == '__main__':
  171. app.debug = True
  172. # app.debug = False
  173. app.run()