async def signup(request: web.Request): db: Database = request.app["db"] user = request["data"]["user"] wallet_currency = request["data"]["wallet_currency"] async with db.connection() as con: # Checking login uniqueness login_exists = await con.fetch_val( sa.select([ sa.exists(users.select().where(users.c.login == user["login"])) ])) if login_exists: return json_response({"user": { "login": "******" }}, status=422) user["password"] = pbkdf2_sha256.hash(user["password"]) # Use transaction to make sure both user and wallet are created async with con.transaction(): # Creating user user_id = await con.fetch_val( users.insert().values(user).returning(users.c.id)) # Creating user wallet await con.execute(wallets.insert().values(user_id=user_id, amount=0, currency=wallet_currency) ) return json_response({})
async def build_report_response(self) -> web.StreamResponse: """ Stream report file to client without saving whole file in memory """ if not self.user_id: # If it is not authorized request try: login = self.query_params["user_login"] except KeyError: return json_response({"user_login": "******"}, status=422) user_id = await self.db.fetch_val( sa.select([users.c.id]).where(users.c.login == login)) if not user_id: return json_response({}, status=404, error="User not found") self.user_id = user_id # Building query based on report type query = build_report_query( self.user_id, self.report_type, date_from=self.query_params.get("date_from"), date_to=self.query_params.get("date_to"), ) # Preparing streaming response response = web.StreamResponse( status=200, headers={"Content-Type": self.content_type}) await response.prepare(self.request) await self.stream_report(response, query) await response.write_eof() return response
async def login(request: web.Request): db: Database = request.app["db"] redis: Redis = request.app["redis"] user = request["data"] actual_user = await db.fetch_one( sa.select([users.c.id, users.c.password]).where(users.c.login == user["login"])) # Login not found if not actual_user: return json_response({}, status=401) # Password is incorrect if not pbkdf2_sha256.verify(user["password"], actual_user["password"]): return json_response({}, status=401) session_token = str(uuid.uuid4()) await redis.setex( key=session_token, value=actual_user["id"], seconds=request.app["config"]["SESSION_EXPIRES"], ) return json_response({"token": session_token})
def submit_temp(): if request.content_type != JSON_MIME_TYPE: error = json.dumps({'error': 'Invalid Content Type'}) return json_response(error, 400) data = request.json if not data.get('temp'): error = json.dumps({'error': 'Missing field (temp)'}) return json_response(error, 400) temp = Temp(temperature=data['temp']) db.session.add(temp) db.session.commit() sio.emit('new_temp', {'data': data['temp']}) return jsonify({'success': temp.temperature}), 201
def configurations(): headers = {'X-Dif-Platform': 'android'} r = requests.get('https://dif-dot-prd-euw-gmal-mcdonalds.appspot.com/plexure/v1/cfg/v3/configurations', headers=headers) if r.status_code != 200: return utils.request_error(r) x = json.loads(r.content.decode()) if config.override_assets: server_url = config.server_external_url x['activityApiUrl'] = '{}/act/v3'.format(server_url) x['advertisementApiUrl'] = '{}/adv/v3'.format(server_url) x['advertisementImagePrefix'] = '{}/images'.format(server_url) x['assetsDownloadPrefix'] = '{}/images'.format(server_url) x['authorizationApiUrl'] = '{}/auth'.format(server_url) x['categoryImagePrefix'] = '{}/images'.format(server_url) x['configurationApiUrl'] = '{}/cfg/v3'.format(server_url) x['consumerApiUrl'] = '{}/con/v3'.format(server_url) x['locationApiUrl'] = '{}/loc/v3'.format(server_url) x['offerApiUrl'] = '{}/off/v3'.format(server_url) x['offerImagePrefix'] = '{}/images'.format(server_url) x['redeemedOfferImagePrefix'] = '{}/images'.format(server_url) return utils.json_response(x)
def list_active_redis_images(): return json_response([{ 'id': i.id, 'name': i.name, 'creation': i.creation, 'description': i.description, } for i in models.cont_image.list_redis()])
def locations(): if 'key' not in request.args: return utils.error('Missing "key" argument.') DEVELOPMENT = 'ODE4NTYzODY1ODY1MDAyNTQ4Mjc2NDIyNTk4MjUwMjI6c3FqNnE3c2pqdDUwZnZ1NXRpaW1kaXJjaHduZG1jNmhjMXAxZ3oyZ3BmMnZsZmg3b2hmdDU3emowcThqNzMyMA==' STAGING = 'OTQ0MjIwMDEzNzUzMzk2OTY2Mzc2MTQyMzM5NjgxNDI6OXY3cHFxMXh0eTVtZnNvNXp4NXJzOXFhcTE2MWh5ZG4wN3l5OG1wcThyNXRycmo4aGJsYzEwNTB6NnFodDlvdQ==' PRODUCTION = 'ODI1OTAzOTI2NzcyNzcxNzcxNTI0MTA5ODk1ODA2NDc6cDFwd3hoanFiM2NiazdyMWlwdXFjeG85MjRreDN1dDQzNDBmd3hvd3pxM3F4bjlidmMzdml0bzlsa2N2NGl0bA==' key = request.args.get('key', PRODUCTION) base_url = 'https://config-api-dot-{}-euw-gmal-mcdonalds.appspot.com' if key == DEVELOPMENT: url = base_url.format('dev') + request.path elif key == STAGING: url = base_url.format('stg') + request.path elif key == PRODUCTION: url = base_url.format('prd') + request.path params = { 'key': key } headers = { 'User-Agent': 'okhttp/3.12.0' } r = requests.request(request.method, url, params=params, headers=headers) if r.status_code != 200: return utils.request_error(r) x = json.loads(r.content.decode()) return utils.json_response(x)
def post(self): user_id = request.user.id data = request.json poetry_id = data["poetry_id"] m.UserFavorite.add_favorite(user_id, poetry_id) return json_response()
async def get_balance(request: web.Request) -> web.Response: db: Database = request.app["db"] wallet = await db.fetch_one( sa.select([wallets.c.amount, wallets.c.currency ]).where(wallets.c.user_id == request["user_id"])) return json_response(dict(wallet))
def consent(): if request.method == 'GET': return utils.json_response('{"firstName":"McMod","emailAddress":"*****@*****.**"}', dump=False) else: if config.server_debug: print(request.data) return Response(status=201)
def tag_values(): if request.method == 'GET': return utils.json_response('{"tagValueReferenceCodes":["McMod"]}', dump=False) else: if config.server_debug: print(request.data) return Response(status=202)
def post(self): user_id = request.user.id data = request.json interest_ids = data["interest_ids"] m.UserInterest.add_interests(user_id, interest_ids) return json_response()
def get(item_id): """ Get a specific item """ data = ItemController.get(ItemController.decode_id(item_id)) data.pop('user_id', None) return json_response(data)
def post(self): data = request.json code = data["code"] wechat_user = m.WechatUser.get_or_create_by_mp_code(code) request.user = wechat_user.user return json_response()
def terms_and_conditions(offer): headers = mcdutils.get_random_headers() r = requests.get('https://dif-dot-prd-euw-gmal-mcdonalds.appspot.com/plexure/v1/off/v3/offers/{}/termsAndConditions' .format(offer), headers=headers) x = json.loads(r.content.decode()) return utils.json_response(x)
def get_masters_info(): try: masters, myself = masters_detail(request.args['host'], int(request.args['port'])) return json_response({ 'masters': masters, 'myself': { 'role': myself.role_in_cluster, 'slots': len(myself.assigned_slots), }, }) except IOError: return json_response({ 'masters': [], 'myself': { 'role': 'master', 'slots': 0 }, })
def get(self): data = request.args page = int(data.get("page", 1)) ipp = int(data.get("ipp", 10)) total = m.Interest.select().count() interests = m.Interest.list_interests(page, ipp) data = {"total": total, "page": page, "ipp": ipp, "objects": interests} return json_response(data)
def list_clusters(): r = [] for c in models.cluster.list_all(): if len(c.nodes) == 0: continue r.append({ 'id': c.id, 'descr': c.description, 'nodes': len(c.nodes), 'node0': {'host': c.nodes[0].host, 'port': c.nodes[0].port}, }) return json_response(r)
def cluster_auto_discover(): host = request.args['host'] port = int(request.args['port']) try: nodes = redistrib.command.list_nodes(host, port, host)[0] except StandardError as e: logging.exception(e) raise ValueError(e) if len(nodes) <= 1 and len(nodes[0].assigned_slots) == 0: return json_response({'cluster_discovered': False}) return json_response({ 'cluster_discovered': True, 'nodes': [{ 'host': n.host, 'port': n.port, 'role': n.role_in_cluster, 'known': nm.get_by_host_port(n.host, n.port) is not None, } for n in nodes], })
def advertisements(): if 'X-Vmob-Cost-Center' not in request.headers: abort(500) merchant_id = int(request.headers['X-Vmob-Cost-Center'][-3:]) URL = 'https://dif-dot-prd-euw-gmal-mcdonalds.appspot.com/plexure/v1/adv/v3/advertisements?offset=0&merchantId={}&ignoreDailyTimeFilter=false&limit=100&placement=CD'.format(merchant_id) headers = get_authorization() r = requests.get(URL, headers=headers) return utils.json_response(json.loads(r.content.decode()))
def _simple_cmd(host, port, *command): status = 200 try: with Connection(host, port) as t: try: r = t.talk(*command) except ReplyError as e: r = {'reason': e.message} status = 400 except IOError: status = 400 r = {'reason': 'not reachable'} return json_response(r, status)
def get(self): user_id = request.user.id data = request.args page = int(data.get("page", 1)) ipp = int(data.get("ipp", 10)) total = m.UserFavorite.select().where( m.UserFavorite.user_id == user_id).count() favorites = m.UserFavorite.list_favorites(user_id, page, ipp) data = {"total": total, "page": page, "ipp": ipp, "objects": favorites} return json_response(data)
def language_strings(language, country): r = requests.get('https://storage.googleapis.com/prd-euw-gmalstring-mcdonalds' + request.path) if r.status_code != 200: return utils.request_error(r) x = json.loads(r.content.decode()) # Customize strings x['gmal_error_general_title'] = translations.get_string('generic_error_title', language) x['gmal_error_general_body'] = translations.get_string('generic_error_body', language) return utils.json_response(x)
def device_registration(): x = { 'access_token': 'from_hexile_with_love', 'token_type': 'ffapi_project', 'consumerInfo': { 'firstName': 'McMod', 'emailAddress': 'McMod' }, 'crossReferences': None, 'jwtAccessToken': None, 'jwtRefreshToken': None } return utils.json_response(x)
def v3_offers(): if 'X-Vmob-Cost-Center' not in request.headers: abort(500) merchant_id = int(request.headers['X-Vmob-Cost-Center'][-3:]) language = 'en' if 'Accept-Language' in request.headers: language = request.headers['Accept-Language'].split('-')[0] merchant_offers = offers.get_offers(merchant_id) for x in merchant_offers: x['image'] = 'op{}_{}-1.png'.format(x['id'], language) return utils.json_response(merchant_offers)
def get_task_steps(): t = models.task.get_task_by_id(int(request.args['id'])) if t is None: return abort(404) return json_response([{ 'id': step.id, 'command': step.command, 'args': step.args, 'status': 'completed' if step.completed else ('running' if step.running else 'pending'), 'start_time': f_strftime(step.start_time), 'completion': f_strftime(step.completion), 'exec_error': step.exec_error, } for step in t.all_steps])
def index(): """ Get items form database. If category args is not provided, recently added items is returned. """ page = 1 per_page = 25 if request.args.get('page'): page = request.args['page'] if request.args.get('per_page'): per_page = request.args['per_page'] category = request.args.get('category', None) if category: category = CategoryController.decode_id(category) data = ItemController.index(category_id=category, page=page, per_page=per_page) return json_response(data)
async def put_money_on_balance(request: web.Request) -> web.Response: db: Database = request.app["db"] money = request["data"] rates = await request.app["rates_client"].get_rates() async with db.connection() as con: wallet = await con.fetch_one( sa.select([wallets.c.amount, wallets.c.currency ]).where(wallets.c.user_id == request["user_id"])) new_amount = wallet["amount"] + convert_amount( rate_from=rates[money["currency"]], rate_to=rates[wallet["currency"]], amount=money["amount"], ) await con.execute(wallets.update().values(amount=new_amount).where( wallets.c.user_id == request["user_id"])) return json_response({ "amount": new_amount, "currency": wallet["currency"] })
def locationfinder(): if 'key' not in request.args: return utils.error('Missing "key" argument.') DEVELOPMENT = 'NjE3MjgxMjMwNDY3MDY5NTcwMTMwNTQwMjExODY1NDQ6YTNzdWsxcGsxNW1peHdybnBtZ2pwdXNmODMyNzNhOGgwbXR4ejk3NmU2b29iam1xNzV4Nmppb21panE2eWljcg==' STAGING = 'NzUyMzE2NzQyMjI0NjUyMTY0NDQ2NDI4NjI5ODA1NTE6cGE5ZTdlOHYyeGN0bWo2Nml1NGhldjMzbGNhajA1czJlMnF5c3RkaXAwaWRnNTRrdnc5eDllcnBmeWR2c3E2cw==' PRODUCTION = 'MDAwNzc3Mzg4MTg5MDI0OTM5NzI1MjE4OTA5MTgyNDY6bWE4bDNjeTh6cmkydHNnMWZicjMwMGpiYWY5NXZ1aTFpc2hmNW0xdTBsNzRlcXZraHVncmEwaTJ1aGQ4amlqZA==' key = request.args.get('key', PRODUCTION) base_url = 'https://locationfinder-api-dot-{}-euw-gmal-mcdonalds.appspot.com' if key == DEVELOPMENT: url = base_url.format('dev') + request.path elif key == STAGING: url = base_url.format('stg') + request.path elif key == PRODUCTION: url = base_url.format('prd') + request.path params = { 'key': key } headers = { 'User-Agent': 'okhttp/3.12.0' } location = { 'country': { 'name': 'Italy', 'code': 'IT' }, 'location': { 'latitude': 0.0, 'longitude': 0.0 } } return utils.json_response(location)
async def change_status(request: web.Request) -> web.Response: db: Database = request.app["db"] operation_id = int(request.match_info["operation_id"]) new_status = request["data"]["status"] async with db.connection() as con: operation = await con.fetch_one( sa.select([*operations.c, operations_statuses.c.status]).select_from( operations.join(operations_statuses)).where( operations.c.id == operation_id).order_by( sa.desc(operations_statuses.c.id)).limit(1)) if not operation: return json_response({}, status=404, error="Operation not found") if new_status not in ALLOWED_TRANSACTIONS[operation["status"]]: return json_response({}, status=400, error="Not valid status") async with con.transaction(): if (operation["status"] == OperationStatuses.DRAFT and new_status == OperationStatuses.PROCESSING): sender_wallet = await con.fetch_one(wallets.select().where( wallets.c.id == operation["sender_wallet_id"])) amount_from_sender = convert_amount( rate_to=operation["sender_wallet_rate"], amount=operation["amount"]) if sender_wallet["amount"] < amount_from_sender: return json_response( {}, status=202, error="Not enough money on sender wallet") new_sender_amount = sender_wallet["amount"] - amount_from_sender await con.execute( sa.update(wallets).values(amount=new_sender_amount).where( wallets.c.id == operation["sender_wallet_id"])) elif operation["status"] == OperationStatuses.PROCESSING: if new_status == OperationStatuses.ACCEPTED: amount_to_receiver = convert_amount( rate_to=operation["receiver_wallet_rate"], amount=operation["amount"], ) await con.execute( sa.update(wallets).values(amount=wallets.c.amount + amount_to_receiver). where(wallets.c.id == operation["receiver_wallet_id"])) elif new_status == OperationStatuses.FAILED: amount_to_sender = convert_amount( rate_to=operation["sender_wallet_rate"], amount=operation["amount"], ) await con.execute( sa.update(wallets).values( amount=wallets.c.amount + amount_to_sender).where( wallets.c.id == operation["sender_wallet_id"])) await con.execute(operations_statuses.insert().values( operation_id=operation_id, status=new_status, datetime=dt.datetime.utcnow(), )) operation = dict(operation) operation["status"] = new_status operation["datetime"] = operation["datetime"].isoformat() return json_response(operation)