def to_entity(self, data: User) -> str: datas = str(data) query = '' for i in datas.split(','): temp = data.to_dict().get(i.strip()) if (temp): type_data = data.define_type(i.strip()) query += '{} = {},'.format( i.strip(), self.conversor.to_entity(type_data, temp)) query = query[:-1] return query
def validate_object_update(self, data: Any) -> (str, User): id = data['id'] if ('id' in data) else None name = data['name'] if ('name' in data) else None lastName = data['lastName'] if ('lastName' in data) else None email = data['email'] if ('email' in data) else None isValid = data['isValid'] if ('isValid' in data) else None photoUrl = data['photoUrl'] if ('photoUrl' in data) else None createdAt = data['createdAt'] if ('createdAt' in data) else None updatedAt = data['updatedAt'] if ('updatedAt' in data) else None deletedAt = data['deletedAt'] if ('deletedAt' in data) else None if not (self.name_validation(name) if (name) else True): return ('name not valid', {}) if not (self.lastname_validation(lastName) if (lastName) else True): return ('last name not valid', {}) if not (self.email_validation(email) if (email) else True): return ('email not valid', {}) if not (self.is_valid_validation(isValid) if (isValid) else True): return ('is valid not valid', {}) if not (self.photo_url_validation(photoUrl) if (photoUrl) else True): return ('photo url not valid', {}) if not (self.created_at_validation(createdAt) if (createdAt) else True): return ('created at not valid', {}) if not (self.updated_at_validation(updatedAt) if (updatedAt) else True): return ('updated at not valid', {}) return ('done correctly', User(id, name, lastName, email, photoUrl, isValid, createdAt, updatedAt, deletedAt))
def to_entity(self, data: User) -> (str, str): datas = str(data) query = definitions = '' for i in datas.split(','): temp = data.to_dict().get(i.strip()) if (temp): type_data = data.define_type(i.strip()) query += self.conversor.to_entity(type_data, temp) definitions += i.strip() query += ',' definitions += ',' query = query[:-1] definitions = definitions[:-1] return (query, definitions)
def test_post(self): ur = UserCreateResource() res = ur.post() self.assertEqual(res.status_code, 201) ur1 = UserResource() user = User.from_json(res.data) ur1.delete(str(user.id))
def test_get_right(self): ur = UserResource() ucr = UserCreateResource() res = ucr.post() user = User.from_json(res.data) res = ur.get(str(user.id)) self.assertEqual(res.status_code, 200) ur.delete(str(user.id))
def get_real_user_by_token(self, token): user = self.get_by_token(token) if user is None: return user return User(user_id=user.mongo_id, l_name=user.l_name, admin=user.admin, status=user.status)
def get(self, user_id): if self.exists(user_id): user = Users.query.get(user_id) return User(user_id=user.mongo_id, l_name=user.l_name, admin=user.admin, status=user.status) else: return None
def test_get_right(self, mock_user): user = User(user_id="123", ticket_ids="012", name="name", password="******") mock_user.return_value.get.return_value = user ur = UserResource() res = ur.get("123") self.assertEqual(res.status_code, 200)
def to_query(self, id: int) -> str: user_temp = User(0, 0, 0, 0, 0, 0, 0, 0, 0) query = '{}=FALSE, {}={} WHERE {}={} RETURNING *;'.format( user_temp.validation_name(), user_temp.delete_date_name(), self.conversor.to_entity( user_temp.define_type(user_temp.delete_date_name()), datetime.datetime.now()), user_temp.id_name(), id) return query
def execute( self, limit: int, offset: int ) -> List[User]: cursor = self.__database.get_cursor() cursor.execute(self.query) rows = cursor.fetchall() rows = list(map(self.minimize_str, rows)) return [User(*row) for row in rows]
def get(self, user_id): if self.exists(user_id): user = Users.query.get(user_id) ticket_ids = jsonpickle.decode(user.ticket_ids) return User(user_id=user.mongo_id, ticket_ids=ticket_ids, name=user.name, password=user.password) else: return None
def test_get_right(self): rep = UserRepository() user_id = rep.create('name', 'password') user1 = rep.get(user_id) user2 = User(user_id=fields.ObjectId(user_id), ticket_ids=[], name='name', password='******') self.assertEqual(user1, user2) rep.delete(user_id)
def test_get(self, mock_user): users = [] user = User(user_id="123", ticket_ids="012", name="name", password="******") users.append(user) mock_user.return_value.read_paginated.return_value = users, False, True ur = UserListResource() res = ur.get() self.assertEqual(res.status_code, 200)
def test_post(self): payload = {'name': 'test', 'password': '******'} res = requests.post(current_config.USER_SERVICE_URL + current_config.USER_SERVICE_PATH + current_config.CREATE_PATH, data=jsonpickle.encode(payload)) self.assertEqual(res.status_code, 201) user = User.from_json(res.content) requests.delete(current_config.USER_SERVICE_URL + current_config.USER_SERVICE_PATH + "/%s" % str(user.id))
def execute(self, data: User) -> User: query_data = self.query + self.to_query(data) cursor = self.__database.get_cursor() cursor.execute(query_data) new_user = cursor.fetchone() self.__database.get_connection().commit() cursor.close() new_user = self.minimize_str(new_user) return User(*new_user)
def execute(self, data: User, id: int) -> User: query_data = self.query + self.to_query(data, id) cursor = self.__database.get_cursor() cursor.execute(query_data) updated_user = cursor.fetchone() self.__database.get_connection().commit() cursor.close() updated_user = self.minimize_str(updated_user) return User(*updated_user)
def read_paginated(self, page_number, page_size): users = [] users_paged = Users.query.paginate(page=page_number, per_page=page_size) for user in users_paged.items: users.append( User(user_id=user.mongo_id, status=user.status, l_name=user.l_name, admin=user.admin)) is_prev_num = (users_paged.prev_num > 0) is_next_num = (users_paged.next_num <= users_paged.pages) return users, is_prev_num, is_next_num
def execute(self, id: int) -> User: query_data = self.query + self.to_query(id) print('query_data - {}'.format(query_data)) cursor = self.__database.get_cursor() cursor.execute(query_data) get_user = cursor.fetchone() cursor.close() print('get_user - {}'.format(get_user)) if not (get_user): return None get_user = self.minimize_str(get_user) return User(*get_user)
def read_paginated(self, page_number, page_size): users = [] users_paged = Users.query.paginate(page=page_number, per_page=page_size) for user in users_paged.items: ticket_ids = jsonpickle.decode(user.ticket_ids) users.append( User(user_id=user.mongo_id, ticket_ids=ticket_ids, name=user.name, password=user.password)) is_prev_num = (users_paged.prev_num > 0) is_next_num = (users_paged.next_num <= users_paged.pages) return users, is_prev_num, is_next_num
def test_delete_right(self): sr = FixResource() ur = UserResource() scr = FixCreateResource() r = scr.post() fix = Fix.from_json(r.data) u = UserCreateResource() us = u.post() user = User.from_json(us.data) payload = {'fix_id': fix.id, 'name': 'suzuki', 'user_id': user.id} res = requests.post(current_config.GATEWAY_URL + current_config.GATEWAY_PATH + '/cars/add', data=jsonpickle.encode(payload)) #sr.delete(fix.id) car = Car.from_json(res.content) ret_prod = GatewayReturnCar() res = ret_prod.delete(car.id) self.assertEqual(res.status_code, 204) ur.delete(user.id) sr.delete(fix.id)
def execute(self, filters: Filter_Interface, attributes: List[Attribute_Filter], joins: Any, limit: int, offset: int) -> (List[User], str): query_filter = query_count = self.query query_filter += self.convert_attributes(attributes) query_count += self.convert_attributes(attributes, is_count=True) query_filter += ' FROM ' query_count += ' FROM ' query_filter += self.definitor() query_count += self.definitor() query_filter += self.convert_joins(joins) query_count += self.convert_joins(joins) query_filter += ' WHERE ' query_count += ' WHERE ' query_filter += self.convert_filter(filters) query_count += self.convert_filter(filters) query_filter += self.convert_limit_offset(limit, offset) cursor = self.__database.get_cursor() cursor.execute(query_filter) rows = cursor.fetchall() rows = list(map(self.minimize_str, rows)) return ([User(*row) for row in rows], query_count)
def delete(self, prod_id): app.logger.info('Получен запрос на возврат товара') req = requests.session() for cookie in flask.request.cookies: req.cookies[cookie] = flask.request.cookies[cookie] cookies = req.cookies token = cookies['token'] response = requests.get(current_config.USER_SERVICE_URL + current_config.USER_SERVICE_PATH + "/token", data=jsonpickle.encode({'token':token})) result = flask.Response(status=response.status_code, headers=response.headers.items(), response=response.content) if result.status_code != 200: return result user = User.from_json(response.content) user_id = user.id response = requests.get(current_config.PROD_SERVICE_URL + current_config.PROD_SERVICE_PATH + "/%s" % prod_id) if response.status_code == 200: app.logger.info('Запрос на получение информации о товаре с идентификатором %s успешно обработан' % prod_id) else: app.logger.warning('Информация о товаре с идентификатором %s не может быть получена' % prod_id) result = flask.Response(status=response.status_code, headers=response.headers.items(), response=response.content) return result prod = Prod.from_json(response.content) payload1 = {'cell': prod.cell, 'status': 'return'} try: response = requests.patch(current_config.MAG_SERVICE_URL + current_config.MAG_SERVICE_PATH + "/%s" % prod.mag_id, jsonpickle.encode(payload1)) if response.status_code == 201: app.logger.info('Освобождение места на витрине в магазине успешно завершен') else: app.logger.warning('Освобождение места на витрине в магазине не может быть завершено, добавляем запрос в очередь') replay_request_queue.send_message( jsonpickle.encode(Request("PROD_RETURN", data={"mag_id": prod.mag_id, "payload": payload1})), "prod_return_handling_request") except: app.logger.warning( 'Освобождение места на витрине в магазине не может быть завершено, добавление запроса в очередь') replay_request_queue.send_message(jsonpickle.encode(Request("PROD_RETURN", data={"mag_id": prod.mag_id, "payload": payload1})), "prod_return_handling_request") finally: payload3 = {'prod_id': prod_id, 'status': 'return'} response = requests.patch(current_config.USER_SERVICE_URL + current_config.USER_SERVICE_PATH + "/%s" % user_id, jsonpickle.encode(payload3)) if response.status_code == 201: app.logger.info('Возврат товара для пользователя %s успешно произведен' % user_id) else: payload1['status'] = 'buy' requests.patch(current_config.MAG_SERVICE_URL + current_config.MAG_SERVICE_PATH + "/%s" % prod.mag_id, jsonpickle.encode(payload1)) app.logger.warning('Возврат товара для пользователя %s не может быть произведен' % user_id) result = flask.Response(status=response.status_code, headers=response.headers.items(), response=response.content) return result response = requests.delete(current_config.PROD_SERVICE_URL + current_config.PROD_SERVICE_PATH + "/%s" % prod_id) result = flask.Response(status=response.status_code, headers=response.headers.items(), response=response.content) if response.status_code == 204: app.logger.info('Товар с идентификатором %s успешно удален' % prod_id) else: payload1['status'] = 'buy' requests.patch(current_config.MAG_SERVICE_URL + current_config.MAG_SERVICE_PATH + "/%s" % prod.mag_id, jsonpickle.encode(payload1)) payload3['status'] = 'buy' requests.patch(current_config.USER_SERVICE_URL + current_config.USER_SERVICE_PATH + "/%s" % user_id, jsonpickle.encode(payload3)) app.logger.warning('Товар с идентификатором %s не может быть удален' % prod_id) return result
def post(self): app.logger.info('Получен запрос на покупку билета') req = requests.session() for cookie in flask.request.cookies: req.cookies[cookie] = flask.request.cookies[cookie] cookies = req.cookies token = cookies['token'] response = requests.get(current_config.USER_SERVICE_URL + current_config.USER_SERVICE_PATH + "/token", data=jsonpickle.encode({'token':token})) result = flask.Response(status=response.status_code, headers=response.headers.items(), response=response.content) if result.status_code != 200: return result user = User.from_json(response.content) user_id = user.id payload = jsonpickle.decode(flask.request.data) payload1 = {'cell': payload["cell"], 'status': 'buy'} response = requests.patch(current_config.MAG_SERVICE_URL + current_config.MAG_SERVICE_PATH + "/%s" % payload["mag_id"], jsonpickle.encode(payload1)) result = flask.Response(status=response.status_code, headers=response.headers.items(), response=response.content) if result.status_code != 201: app.logger.error('Покупка товара в магазине с идентификатором %s не может быть выполнена' % payload["mag_id"]) return result else: app.logger.info('Пользователь %s взял товар с полки в магазине с идентификатором %s' % (user_id, payload["mag_id"])) response = requests.post(current_config.PROD_SERVICE_URL + current_config.PROD_SERVICE_PATH + current_config.CREATE_PATH, jsonpickle.encode(payload)) prod = Prod.from_json(response.content) if response.status_code == 201: app.logger.info('Товра с идентификатором %s успешно создан' % str(prod.id)) else: payload1['status'] = 'return' requests.patch(current_config.MAG_SERVICE_URL + current_config.MAG_SERVICE_PATH + "/" + payload["mag_id"], jsonpickle.encode(payload1)) app.logger.warning('Товар не может быть создан') result = flask.Response(status=response.status_code, headers=response.headers.items(), response=response.content) return result result = flask.Response(status=response.status_code, headers=response.headers.items(), response=response.content) payload3 = {'prod_id': str(prod.id), 'status': 'buy'} response = requests.patch(current_config.USER_SERVICE_URL + current_config.USER_SERVICE_PATH + "/%s" % user_id, jsonpickle.encode(payload3)) if response.status_code == 201: app.logger.info('Покупка товара для пользователя успешно произведена') else: result = flask.Response(status=response.status_code, headers=response.headers.items(), response=response.content) payload1['status'] = 'return' requests.patch(current_config.MAG_SERVICE_URL + current_config.MAG_SERVICE_PATH + "/" + payload["mag_id"], jsonpickle.encode(payload1)) requests.delete(current_config.PROD_SERVICE_URL + current_config.PROD_SERVICE_PATH + "/" + payload3['prod_id']) app.logger.warning('Покупка товара не может быть завершена') return result
def to_query(self, data: int) -> str: user_temp = User(0,0,0,0,0,0,0,0,0) return ' WHERE {} = {} AND {} = TRUE;'.format(user_temp.id_name(), data, user_temp.validation_name())
def to_query(self, data: User, id: int) -> str: definitions = self.to_entity(data) user_temp = User(0, 0, 0, 0, 0, 0, 0, 0, 0) query = '{} WHERE {}={} RETURNING *;'.format(definitions, user_temp.id_name(), id) return query
def post(self): app.logger.info('Получен запрос на починку автомобиля') paybuy = jsonpickle.decode(flask.request.data) req = requests.session() for cookie in flask.request.cookies: req.cookies[cookie] = flask.request.cookies[cookie] cookies = req.cookies token = cookies['token'] response = requests.get(current_config.USER_SERVICE_URL + current_config.USER_SERVICE_PATH + "/token", data=jsonpickle.encode({'token': token})) result = flask.Response(status=response.status_code, headers=response.headers.items(), response=response.content) if result.status_code != 200: return result user = User.from_json(response.content) paybuy1 = { 'fix_id': str(paybuy["fix_id"]), 'user_id': user.id, 'name': str(paybuy["name"]) } response = requests.post( current_config.CAR_SERVICE_URL + current_config.CAR_SERVICE_PATH + current_config.CREATE_PATH, jsonpickle.encode(paybuy1)) car = Car.from_json(response.content) if response.status_code == 201: app.logger.info('Товар с идентификатором %s успешно создан' % str(car.id)) else: app.logger.warning('Товар не может быть создан') result = flask.Response(status=response.status_code, headers=response.headers.items(), response=response.content) return result result = flask.Response(status=response.status_code, headers=response.headers.items(), response=response.content) paybuy2 = {'car_id': str(car.id), 'status': 'fix'} response = requests.patch( current_config.FIX_SERVICE_URL + current_config.FIX_SERVICE_PATH + "/%s" % paybuy["fix_id"], jsonpickle.encode(paybuy2)) if response.status_code == 201: app.logger.error('Заявки в мастерскую %s оформлена' % paybuy["fix_id"]) else: result = flask.Response(status=response.status_code, headers=response.headers.items(), response=response.content) app.logger.info('Магазин %s не существуета' % (paybuy["fix_id"])) requests.delete(current_config.CAR_SERVICE_URL + current_config.CAR_SERVICE_PATH + "/" + paybuy2['car_id']) return result paybuy3 = {'status': 'fix'} response = requests.patch( current_config.USER_SERVICE_URL + current_config.USER_SERVICE_PATH + "/%s" % paybuy1["user_id"], jsonpickle.encode(paybuy3)) if response.status_code == 201: app.logger.info('Услуга успешно заказана') else: result = flask.Response(status=response.status_code, headers=response.headers.items(), response=response.content) paybuy2['status'] = 'return' requests.patch( current_config.FIX_SERVICE_URL + current_config.FIX_SERVICE_PATH + "/%s" % paybuy["fix_id"], jsonpickle.encode(paybuy1)) requests.delete(current_config.CAR_SERVICE_URL + current_config.CAR_SERVICE_PATH + "/" + paybuy2['car_id']) app.logger.warning('Услуга не может быть заказана') return result