async def post(self): try: json_data = json.loads(self.request.body.decode('utf-8')) print(json_data) data = json_data['data'] json_user = data['user'] posted_user = UserSchema().load(json_user) # validate, check password, and return JWT with self.make_session() as session: user_object = await as_future(session.query(User).\ filter(User.email == posted_user.data['email']).first) if user_object is not None: if verify_password(user_object.password, posted_user.data['password']): self.encoded = jwt.encode({'iat': datetime.now().timestamp()},\ os.environ.get('JWT_SECRET'),\ algorithm='HS256') user_resp = UserSchema(only=('id', 'username', 'email'))\ .dump(user_object) resp_dic = { 'user': user_resp.data, 'jwt': self.encoded.decode('ascii') } self.respond(resp_dic, 'Success', 200) else: print('Password Incorrect.') self.respond(msg='Password Incorrect.', code=400) else: print('Email Incorrect.') self.respond(msg='Incorrect Email.', code=400) except KeyError as e: self.respond(msg=str(e), code=500)
async def post(self): try: json_data = json.loads(self.request.body.decode('utf-8')) data = json_data['data'] json_user = data['user'] posted_user = UserSchema().load(json_user) # validate, hash the password, and save with self.make_session() as session: count = await as_future( session.query(User).filter( or_(User.username == posted_user.data['username'], User.email == posted_user.data['email'])).count) # todo - validate each field individually # make sure username/email is unique if count == 0: posted_user.data['password'] = hash_password( posted_user.data['password']) user = User(**posted_user.data) with self.make_session() as session: session.add(user) session.commit() self.respond(msg="Success", code=200) else: self.respond(data=None, msg="User already exists!", code=200) except KeyError as e: self.respond(msg=str(e), code=500)
async def get(self): with self.make_session() as session: user_objects = await as_future(session.query(User).all) # transforming into JSON-serializable objects if len(user_objects) != 0: schema = UserSchema(many=True) users = schema.dump(user_objects) self.respond(users.data, "Success", 200) else: self.respond(msg="No Users!")
async def get(self, uid): with self.make_session() as session: user_object = await as_future( (session.query(User).filter(User.id == uid).first)) # transforming into JSON-serializable objects if user_object is not None: schema = UserSchema(only=("id", "username", "email", "gravatar")) user = schema.dump(user_object) self.respond(user.data, "Success", 200) else: self.respond(msg="No User with that id!")
def getUsers(): #pra manusear os argumentos do flask try: if int(request.args['per_page']): per_page = int(request.args['per_page']) except: per_page = 3 try: if int(request.args['page']): page = int(request.args['page']) except: page = 1 #pegando os dados da API web req = urllib.request.Request(API_URL.format(page, per_page), headers=headers) with urllib.request.urlopen(req) as response: data = json.loads(response.read().decode()) api_users = data['data'] api_total = int(data['total']) #pegando os dados do TINYDB tinydb_users = db.table('users').all() # transofrmando em json schema = UserSchema(many=True) dados = schema.dump(api_users) #montando a resposta final total = api_total + len(db.table('users')) data = api_users #juntando as duas API caso a URL não for suficiente if len(api_users) != per_page: if (len(api_users) != 0): datamin = 0 else: datamin = ceil(((page * per_page) - api_total) / per_page) - 1 datamax = datamin + per_page dadostotal = api_users + tinydb_users data = dadostotal[datamin:datamax] res = { "page": page, 'per_page': per_page, "total": total, 'total_pages': ceil(total / per_page), "data": data } return jsonify(res)
def addUser(): # montar o usuário posted_user = UserSchema(only=('email', 'first_name', 'last_name', 'avatar')).load(request.get_json()) user = User(**posted_user.data) # salvar db.table('users').insert(user.save()) # retornar novo_user = UserSchema().dump(user).data return jsonify(novo_user), 201
def updateUser(id): # montar o usuário posted_user = UserSchema(only=('email', 'first_name', 'last_name', 'avatar')).load(request.get_json()) user = User(**posted_user.data) #bom, temos dois casos aqui, se for pra editar um usuário da API, então salva ele editado no banco de dados, caso contrário edite ele. #pegando os dados da API web req = urllib.request.Request(API_URL.format(id, 1), headers=headers) with urllib.request.urlopen(req) as response: data = json.loads(response.read().decode()) api_user = data['data'] if (len(api_user) > 0): #se existe é na APIWEB # caso a API fosse integrada #deleteFromAPI(id) # salvar no banco de dados local db.table('users').insert(user.save()) else: #caso contrário edita no banco api_total = int(data['total']) idtinyDB = id - api_total db.table('users').update(user.save(), doc_ids=[idtinyDB]) return ('', 200)
def getUser(id): per_page = 1 page = id #pegando os dados da API web req = urllib.request.Request(API_URL.format(page, per_page), headers=headers) with urllib.request.urlopen(req) as response: data = json.loads(response.read().decode()) api_users = data['data'] api_total = int(data['total']) #pegando os dados do TINYDB tinydb_users = db.table('users').all() # transofrmando em json schema = UserSchema(many=True) dados = schema.dump(api_users) #montando a resposta final total = api_total + len(db.table('users')) data = api_users #juntando as duas API caso a URL não for suficiente if len(api_users) != per_page: if (len(api_users) != 0): datamin = 0 else: datamin = ceil(((page * per_page) - api_total) / per_page) - 1 datamax = datamin + per_page dadostotal = api_users + tinydb_users data = dadostotal[datamin:datamax] res = data if (len(data) == 0): abort(404) else: return jsonify(res)