Guest User

Untitled

a guest
Jan 19th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.10 KB | None | 0 0
  1. import time, datetime
  2.  
  3. import json
  4. from flask import Flask, redirect, request, render_template
  5. from flask.json import jsonify
  6. from flask_sqlalchemy import SQLAlchemy
  7. from flask_restful import reqparse, abort, Api, Resource
  8. from flask_cors import CORS, cross_origin
  9. from uuid import uuid4
  10.  
  11. app = Flask(__name__)
  12. CORS(app, resources=r'/amil/*')
  13.  
  14. app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/amil.db'
  15.  
  16.  
  17. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  18.  
  19. api = Api(app)
  20.  
  21. CHEADER = {'Allow': 'POST,GET,PUT,DELETE'}, 200, {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST,PUT,GET', 'Access-Control-Allow-Headers': "Content-Type,Authorization"}
  22.  
  23.  
  24. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  25.  
  26. @app.after_request
  27. def after_request(response):
  28. response.headers.add('Access-Control-Allow-Origin', '*')
  29. response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
  30. response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
  31. return response
  32.  
  33.  
  34. def check_authorization(request):
  35. if not request.get('Authorization', None) and request.get('Authorization', None) == 'aksjhd98jdasdo': #UUID
  36. abort(401, message="Authorization required")
  37.  
  38.  
  39.  
  40. userparser = reqparse.RequestParser()
  41. userparser.add_argument('transaction_number', location='json', required=True)
  42. userparser.add_argument('cellphone_area', location='json', type=int, required=True)
  43. userparser.add_argument('cellphone_number', location='json', type=int, required=True)
  44. userparser.add_argument('cpf', location='json', type=int, required=True)
  45. userparser.add_argument('fullname', location='json', required=True)
  46. userparser.add_argument('birthdate', location='json', required=True)
  47. userparser.add_argument('gender_id', location='json', type=int, required=True)
  48. userparser.add_argument('state', location='json', required=True)
  49. userparser.add_argument('city', location='json', required=True)
  50.  
  51. putuser = reqparse.RequestParser()
  52. putuser.add_argument('transaction_number', location='json', required=True)
  53. putuser.add_argument('cellphone_area', location='json', type=int, required=True)
  54. putuser.add_argument('cellphone_number', location='json', type=int, required=True)
  55.  
  56. @app.route('/amil/user_data')
  57. def dummy():
  58. rows = User.query.all()
  59. return render_template("all.html", users=rows), 200
  60.  
  61. def validate_create(args):
  62. try:
  63.  
  64. assert len(args.get('transaction_number')) == 16
  65. assert len(str(args.get('cellphone_area'))) == 2
  66. assert len(str(args.get('cellphone_number'))) == 9
  67. assert len(str(args.get('cpf'))) == 11
  68. assert len(str(args.get('fullname'))) >=3 and len(str(args.get('fullname'))) <= 128
  69. try:
  70. assert datetime.datetime.strptime(args.get('birthdate'), '%Y-%m-%d')
  71. except ValueError:
  72. raise ValueError("Incorrect data format, should be YYYY-MM-DD")
  73. assert args.get('gender_id') >= 1 and args.get('gender_id') <=3
  74. assert len(str(args.get('state'))) == 2
  75. assert len(str(args.get('city'))) <= 128 and len(str(args.get('city'))) >= 3
  76.  
  77. except AssertionError:
  78. raise AssertionError
  79.  
  80. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  81.  
  82. def validate_put(args):
  83. try:
  84.  
  85. assert len(args.get('transaction_number')) == 16
  86. assert len(str(args.get('cellphone_area'))) == 2
  87. assert len(str(args.get('cellphone_number'))) == 9
  88.  
  89. except AssertionError:
  90. raise AssertionError
  91.  
  92. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  93. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  94.  
  95. class UserController(Resource):
  96.  
  97. def post(self):
  98. try:
  99. check_authorization(request.headers)
  100. args = userparser.parse_args()
  101. validate_create(args)
  102. y,m,d = args.get("birthdate").split("-");
  103.  
  104. user = User.query.filter_by(transaction_number=args.get("transaction_number")).first()
  105.  
  106. #criar usuario se jรก existir ativar
  107. if not user:
  108.  
  109. userData = User(transaction_number=args.get("transaction_number"),
  110. cellphone_area=args.get("cellphone_area"),
  111. cellphone_number=args.get("cellphone_number"),
  112. cpf=args.get("cpf"),
  113. fullname=args.get("fullname"),
  114. birthdate=datetime.datetime(int(y), int(m), int(d)),
  115. gender_id=args.get("gender_id"),
  116. state=args.get("state"),
  117. city=args.get("city"),
  118. activated=1
  119. )
  120.  
  121. db.session.add(userData)
  122.  
  123. db.session.commit()
  124.  
  125. msm_return = "novo"
  126.  
  127. else:
  128.  
  129. user.activated = 1
  130. user.updated_at = datetime.datetime.utcnow()
  131. user.deleted_at = None
  132. db.session.commit()
  133. msm_return = "ativado"
  134.  
  135. return {"coisa": msm_return}, 200
  136.  
  137. except AssertionError:
  138. abort(400, message='Field is not in required format')
  139.  
  140. def delete(self):
  141. try:
  142. check_authorization(request.headers)
  143. args = putuser.parse_args()
  144. validate_put(args)
  145. #cancelado
  146. user = User.query.filter_by(transaction_number=args.get("transaction_number")).first()
  147. user.activated = 0
  148. user.updated_at = datetime.datetime.utcnow()
  149. user.deleted_at = datetime.datetime.utcnow()
  150. db.session.commit()
  151.  
  152. return {"error":"", "message":"user has been canceled"}, 200
  153.  
  154. except AssertionError:
  155. abort(400, message='Field is not in required format')
  156.  
  157. def put(self):
  158. try:
  159. check_authorization(request.headers)
  160. args = putuser.parse_args()
  161. # validate_put(args)
  162. #inativar
  163. user = User.query.filter_by(transaction_number=args.get("transaction_number")).first()
  164. user.activated = 0
  165. user.updated_at = datetime.datetime.utcnow()
  166. db.session.commit()
  167.  
  168. return {"error":"", "message":"user has been inatived"}, 200
  169.  
  170. except AssertionError:
  171. abort(400, message='Field is not in required format')
  172.  
  173. return data
  174.  
  175.  
  176. # - - - -- - - - - - - - - - - - - - -- - - - - - - - - - - - - - -- - - - - - - - - - -
  177. ## Database
  178.  
  179. db = SQLAlchemy(app)
  180.  
  181.  
  182. # ------------------------------------
  183. class User(db.Model):
  184. id = db.Column(db.Integer, primary_key=True)
  185. transaction_number = db.Column(db.String(80), unique=True, nullable=False)
  186. cellphone_area = db.Column(db.Integer, nullable=False)
  187. cellphone_number = db.Column(db.Integer, nullable=False)
  188. cpf = db.Column(db.Integer, nullable=False)
  189. fullname = db.Column(db.String(128), nullable=False)
  190. birthdate = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow())
  191. gender_id = db.Column(db.Integer, nullable=False)
  192. state = db.Column(db.String(2), nullable=False)
  193. city = db.Column(db.String(128), nullable=False)
  194. activated = db.Column(db.Integer, nullable=True, default=0)
  195. created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow())
  196. updated_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow())
  197. deleted_at = db.Column(db.DateTime, nullable=True)
  198.  
  199. db.create_all()
  200.  
  201. # - - - -- - - - - - - - - - - - - - -- - - - - - - - - - - - - - -- - - - - - - - - - -
  202.  
  203.  
  204. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  205.  
  206. ##
  207. ## Actually setup the Api resource routing here
  208. ##
  209.  
  210. api.add_resource(UserController, '/amil/user')
  211.  
  212. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  213.  
  214. if __name__ == '__main__':
  215. app.run(debug=True, host="0.0.0.0", threaded=True, port=8889)
Add Comment
Please, Sign In to add comment