async def get_exchange_rate(connection): yesterday = datetime.datetime.now() - datetime.timedelta(days=1) pipe_line = connection.find({ 'date': { '$gte': yesterday.strftime('%Y-%m-%d') } }).sort([('bank', -1), ('currency_name', 1), ('date', 1)]) banks = await pipe_line.distinct('bank') currencies = await pipe_line.distinct('currency_name') result = [] rresult = {} async for res in pipe_line: result.append({ "date": res['date'], "bank": res['bank'], "currency_name": res['currency_name'], "buy": res['buy'], "sale": res['sale'], # "exchange_rate": res['exchange_rate'] }) for i in banks: rresult.update({i: prepare_detail_bank_data(i, result)}) log.debug(rresult) res = prepare_detail_currencies(currencies, rresult) return res
async def post(self): data, is_valid = self.validation_class.is_valid(await self.request.json() if self.request.can_read_body else {}) if not is_valid: log.debug('data is: {0}'.format(data)) return web.json_response(data, status=400) log.debug('data is: {0}'.format(data)) dt = await self.model.create(**data) return web.json_response(self.validation_class.dump(dt), status=201)
def is_json_valid(cls, data, many=None, partial=None, *args, **kwargs): try: validated_data = cls().loads(data, many=many, partial=partial) except ValidationError as err: return err, False except Exception as exc: log.debug('Exception: {0}!'.format(exc)) return {'error': 'Something go wrong!'}, False else: return validated_data, True
async def patch(self): _id = self.request.match_info['id'] d = await self.model.query.where(self.model.id == int(_id)).gino.first() data, is_valid = self.validation_class.is_valid(await self.request.json() if self.request.can_read_body else {}) if not is_valid: log.debug('Validation error!: {0}'.format(is_valid)) return web.json_response(data, status=400) log.debug('All ok! {0}'.format(data)) await d.update(**data).apply() return web.json_response(self.validation_class.dump(d))
async def get(self): _id = self.request.match_info.get('id') # filtered_ = self.filtered_fields if not _id: # data = await self.model.query.gino.all() #if not self.filtered_fields else await self.model.query.filter data = await self.pagination(self.model.query) #if not self.filtered_fields else await self.model.query.filter log.debug('{0}'.format(data)) return web.json_response({'items': self.validation_class.dump(data, many=True)}) data = await self.model.query.where(self.model.id == int(_id)).gino.first() log.debug('{0}'.format(data)) return web.json_response({'items': self.validation_class.dump(data)})
async def save_data(connection, data): c_data = copy.deepcopy(data) date = c_data.pop('date') for item_name, item_values in c_data.items(): for item_val in item_values: res = await connection.find_one({ 'date': date, 'currency_name': item_val.get('currency_name'), 'bank': item_val.get('bank'), }) item_val['buy'] = round(float(item_val.get('buy', 0)), 3) item_val['sale'] = round(float(item_val.get('sale', 0)), 3) log.debug(res) if res and res['_id']: await connection.update_one({'_id': res['_id']}, {'$set': item_val}) # log.debug(f'item val {item_val}') log.debug('Updated one item: {0}'.format(res['_id'])) else: ins = await connection.insert_one(item_val) log.debug('Insert new item: {0}'.format(ins.inserted_id)) log.debug('Save finished!')
async def get_data_from_banks(self, return_type='str'): d = datetime.datetime.now() #- datetime.timedelta(days=1) res = '{0}\n'.format(datetime.datetime.now().strftime( '%Y-%m-%d')) if return_type == 'str' else { 'date': d.strftime('%Y-%m-%d') } async with ClientSession() as session: for bank, bank_map in settings.BANK_API.items(): try: async with session.get(bank_map.get('url')) as resp: if resp.status != 200: if isinstance(res, str): res += '{0}\n {1}\n'.format( bank, 'Can not gate data: {0}'.format( resp.status)) elif isinstance(res, dict): log.debug( 'Can not get data From BANK {0} : {1}'. format(bank, resp.status)) else: json_bank_data = await resp.json() if isinstance(res, str): res += '{0}\n {1}\n'.format( bank, self.parse_json(bank_map, json_bank_data, return_type=return_type)) elif isinstance(res, dict): res.update({ bank: self.parse_json(bank_map, json_bank_data, return_type=return_type) }) except ClientConnectorError as e: if isinstance(res, str): res += '{0}\n {1}\n'.format( bank, 'Can not get data: {0}'.format(e)) elif isinstance(res, dict): log.debug('Can not get data: {0}'.format(e)) return res
def app_task_close(app): for task in asyncio.all_tasks(): log.debug('Task close: {0}'.format(task)) task.cancel() log.debug('Task closed!')
async def task_test(app, first_name='John', last_name='Doe'): log.debug( 'Hi {0} {1} I am a async periodic task!'.format( first_name, last_name) )