async def get(self): # TODO должна быть какая нибудь аутентификация (причем быстрая) try: user_uid = uuid.uuid4().hex query = all_tokens.insert().values((user_uid,)) await self.pg.fetch(query) return Response(body={ "MESSAGE_NAME": "GET_TOKEN", "STATUS": True, "PAYLOAD": { "TOKEN": user_uid, "description": "OK" } }) except Exception as e: logging.debug("handler name - %r, message_name - %r, error decoding - %r", "CreateToken", "GET_TOKEN", e) return Response(body={ "MESSAGE_NAME": "GET_TOKEN", "STATUS": False, "PAYLOAD": { "TOKEN": None, "description": "unknown runtime error" } })
async def _health_check_handler(self, _: Request) -> typing.Optional[Response]: try: await self._mtproto.health_check() return Response(status=200, text="ok") except ConnectionError: return Response(status=500, text="gone")
async def handle(self, request: Request) -> Response: local_token_raw: str = request.match_info["local_token"] if not local_token_raw.isdigit(): return Response(status=400) local_token: int = int(local_token_raw) if local_token not in self._devices: return Response(status=403) device = self._devices[local_token] data = await request.read() status = _player_status(data) if status == UpnpPlayerStatus.PLAYING: device.playing = True if status == UpnpPlayerStatus.ERROR and device.playing: device.errored = True if device.errored and status == UpnpPlayerStatus.NOTHING: device.errored = False device.playing = False await device.reconnect.handle() return Response(status=200)
async def get(self): try: query = GET_MODEL.where(all_tokens.c.token == self.token) result = await self.pg.fetch(query) return Response( body={ "MESSAGE_NAME": "CHECK_TOKEN", "STATUS": True, "PAYLOAD": { "TOKEN_STATUS": True, "NAME_MODELS": result, "description": None } }) except Exception as e: logging.debug( "handler name - %r, message_name - %r, error decoding - %r", "CheckToken", "CHECK_TOKEN", e) return Response( body={ "MESSAGE_NAME": "CHECK_TOKEN", "STATUS": False, "PAYLOAD": { "TOKEN_STATUS": None, "NAME_MODELS": [], "description": "Неизвестная runtime ошибка" } })
async def aws_endpoint(request): # very VERY simple mock of s3 if request.method == 'GET': return Response(text=s3_response) elif request.method == 'PUT': image_data = await request.read() img = Image.open(BytesIO(image_data)) request.app['images'].append((request.path, img.width, img.height)) return Response(text='')
async def handle(self, request: Request) -> Response: password = request.match_info["password"] if password != self._config.web_ui_password: return Response(status=403) remote_token = secret_token() self._devices[remote_token] = WebDevice(f"web @({request.remote})", remote_token, self._devices) return Response(status=200, body=str(remote_token))
async def slack_command(request): action = request.match_info.get('slack_command', None) if not action: log.warning('Got no action.') return Response(body='Bad action') payload = await request.text() result = Dispatcher.dispatch_action(action=action, payload=payload) if not result: return Response(body='Error!!') return json_response(result)
async def get(self, project_name) -> Response: project_doc = self.dbcon.database[project_name].find_one( {"type": "project"}) if project_doc: return Response(status=200, body=self.resource.encode(project_doc), content_type="application/json") return Response( status=404, reason="Project name {} not found".format(project_name))
async def handle_file(self, request: 'web.Request', filename: str, from_index=None) -> 'web.Response': """Handle file requests.""" try: filepath = self._directory.joinpath(filename).resolve() if not self._follow_symlinks: filepath.relative_to(self._directory) except (ValueError, FileNotFoundError) as error: # relatively safe raise HTTPNotFound() from error except Exception as error: # perm error or other kind! request.app.logger.exception(error) raise HTTPNotFound() from error # on opening a dir, load it's contents if allowed if filepath.is_dir(): if filename.endswith('/') or not filename: ret = await self.handle_file(request, filename + 'index.html', from_index=filename) else: # Redirect and add trailing slash so relative links work (Issue #3140) new_url = request.rel_url.path + '/' if request.rel_url.query_string: new_url += '?' + request.rel_url.query_string raise HTTPMovedPermanently(new_url) elif filepath.is_file(): ct, encoding = mimetypes.guess_type(str(filepath)) encoding = encoding or 'utf-8' if ct == 'text/html' and self.modify_html: if sys.version_info[0] == 3 and sys.version_info[1] <= 5: # Python 3.4 and 3.5 do not accept pathlib.Path objects in calls to open() filepath = str(filepath) with open(filepath, 'r', encoding=encoding) as fh: text = fh.read() text = self.transform_html(text) ret = Response(text=text, content_type=ct, charset=encoding) else: ret = FileResponse(filepath, chunk_size=self._chunk_size) elif from_index: filepath = self._directory.joinpath(from_index).resolve() try: return Response(text=self._directory_as_html(filepath), content_type="text/html") except PermissionError: raise HTTPForbidden else: raise HTTPNotFound return ret
async def incoming_request(request): airtable = request.app.plugins['airtable'] payload = await request.json() logger.debug('Incoming Airtable event payload: %s', payload) if payload['token'] != airtable.verify: return Response(status=401) futures = list(_dispatch(airtable.routers['request'], payload, request.app)) if futures: return await _wait_and_check_result(futures) return Response(status=200)
async def get(self, instance_id): instance = session.query(Article).filter( Article.id == instance_id ).first() if not instance: return Response( status=404, body=json.dumps({'not found': 404}), content_type='application/json' ) data = self.resource.render_and_encode(instance) return Response(status=200, body=data, content_type='application/json')
async def get(self, project_name, asset_name) -> Response: asset_doc = self.dbcon.database[project_name].find_one({ "type": "asset", "name": asset_name }) if asset_doc: return Response(status=200, body=self.resource.encode(asset_doc), content_type="application/json") return Response(status=404, reason="Asset name {} not found in project {}".format( asset_name, project_name))
async def return_value(currency: Currency, pool): query = sa.select([ RateOrm.rate.label('current_rate'), func.avg(RateOrm.volume).label('avg_volume') ]).group_by(RateOrm.id).where(RateOrm.currency_id == currency.id).order_by( RateOrm.date.desc()).limit(1) async with pool.transaction() as conn: result = await conn.fetchrow(query) if result is None: return Response(text='not found transaction', status=404) result = Rate(**dict(result)) return Response(body=result.json().encode('utf-8'), content_type='application/json', status=200)
async def handle(self, request: Request) -> Response: password = request.match_info["password"] if password != self._config.web_ui_password: return Response(status=403) token = secret_token() device = WebDevice(f"web @({request.remote})", token) remove = functools.partial(self._remove_device, device) self._devices[device] = debounce = AsyncDebounce(remove, self._config.request_gone_timeout) debounce.update_args() return Response(status=200, body=str(token))
async def slack_api(request): api_plugin = request.app.plugins["api"] try: slack_request = SlackApiRequest.from_request(request) except FailedVerification: logger.info(f"Failed verification to API route {request.url}.") return Response(status=401) futures = list( _dispatch(api_plugin.routers["slack"], slack_request, request.app)) if futures: return await _wait_and_check_result(futures) return Response(status=200)
async def start_timer(self, request): data = await request.json() try: project_name = data['project_name'] asset_name = data['asset_name'] task_name = data['task_name'] hierarchy = data['hierarchy'] except KeyError: log.error("Payload must contain fields 'project_name, " + "'asset_name', 'task_name', 'hierarchy'") return Response(status=400) self.module.stop_timers() self.module.start_timer(project_name, asset_name, task_name, hierarchy) return Response(status=200)
async def _wait_and_check_result(futures): dones, _ = await asyncio.wait(futures, return_when=asyncio.ALL_COMPLETED) try: results = [done.result() for done in dones] except Exception as e: logger.exception(e) return Response(status=500) results = [result for result in results if isinstance(result, Response)] if len(results) > 1: logger.warning('Multiple web.Response for handler, returning none') elif results: return results[0] return Response(status=200)
async def get(self, request: Request) -> Response: auth = False for x in self.allowed_hosts: if request.remote.startswith(x): auth = True break if not auth: _LOGGER.warning( f'unauthorised attempt to connect from {request.remote}') return Response(status=401) hass: HomeAssistant = request.app['hass'] hub: 'h.MegaD' = hass.data.get(DOMAIN).get( request.remote) # TODO: проверить какой remote if hub is None and request.remote == '::1': hub = hass.data.get(DOMAIN).get('__def') if hub is None: return Response(status=400) data = dict(request.query) hass.bus.async_fire( EVENT_BINARY_SENSOR, data, ) _LOGGER.debug(f"Request: %s from '%s'", data, request.remote) make_ints(data) port = data.get('pt') data = data.copy() data['mega_id'] = hub.id ret = 'd' if port is not None: hub.values[port] = data for cb in self.callbacks[hub.id][port]: cb(data) template: Template = self.templates.get(hub.id, {}).get(port) if hub.update_all: asyncio.create_task(self.later_update(hub)) if template is not None: template.hass = hass ret = template.async_render(data) _LOGGER.debug('response %s', ret) ret = Response(body=ret or 'd', content_type='text/plain', headers={ 'Server': 's', 'Date': 'n' }) return ret
async def post(self): status: bool = True result: list = [] try: res: dict = await self.request.json() payload: dict = res["PAYLOAD"] query = select([comments.c.comment ]).where(comments.c.file == payload["url"]) for row in await self.pg.fetch(query): result.append(row['comment']) logging.info("handler name - %r, message_name - %r, info - %r", "GetCommentHandler", "GET_COMMENT", "OK") except Exception as e: status = False logging.info( "handler name - %r, message_name - %r, info - %r, error - %r", "GetCommentHandler", "GET_COMMENT", "FAIL", e) return Response( body={ "MESSAGE_NAME": "GET_COMMENT", "STATUS": status, "PAYLOAD": { "result": result, "description": "OK" } })
async def health_get(request: Request) -> Response: try: return Response(body=json.dumps({"status": "OK"}), headers={'content-type': 'application/json'}) except Exception as ex: log.warning(f"Endpoint: health, Method: get. Error:{str(ex)}") return HTTPInternalServerError()
async def post_db_list_with_historic_metrics(request: Request): configurator: Configurator = request.app["metricq_client"] config_dict = await configurator.get_configs() data = await request.json() db_list = [] for config_id, config in config_dict.items(): if config_id.startswith("db-"): try: db_list.append({ "id": config_id, "metrics": [{ "id": metric_id, "databaseId": config_id, "intervalMin": f"{metric_config['interval_min'] / 1e6:.0f}ms", "intervalMax": f"{metric_config['interval_max'] / 1e6:.0f}ms", "intervalFactor": metric_config["interval_factor"], } for metric_id, metric_config in config["metrics"].items() if metric_id in data["selectedMetrics"]], }) except KeyError: logger.error( f"Config of database {config_id} is incorrect! Missing key" ) except AttributeError: logger.error( f"Config of database {config_id} is incorrect! 'metrics' is list not dict" ) return Response(text=json.dumps(db_list), content_type="application/json")
async def render_page(self, reason=''): """ Получет список изображений из БД и формирует html код страницы :param reason: Текстовое описание причины ошибки :return: Response """ rows_per_page, page = self.fetch_query_data() page = page - 1 order = 'desc', by = 'upload_date' orderby = getattr(Images.c, by, None) if orderby is None: orderby = Images.c.upload_date sort = orderby.desc() if order != 'desc': sort = orderby.asc() query = Images.select()\ .order_by(sort)\ .limit(rows_per_page)\ .offset(rows_per_page*page) query_string, params = asyncpgsa.compile_query(query) res = [] async with self.request.app.db.acquire() as conn: for row in await conn.fetch(query_string, *params): tmp = ImageManager.init_from_db_row(row) res.append(tmp.serialize()) template = self.request.app.jinja.get_template('index.html') data = await template.render_async(res=res, reason=reason) return Response(body=data, status=200, headers={'Content-Type': 'text/html'})
async def post(self): status: bool = True try: res: dict = await self.request.json() payload: dict = res["PAYLOAD"] logging.info("handler name - %r, message_name - %r, info - %r", "AddCommentHandler", "ADD_COMMENT", "OK") # запрос к db на добавление комментария в бд(id, url фото, комментарий, дата) query = comments.insert().values( file=payload["url"], comment=payload["comment"], date=datetime.now() ) await self.pg.fetch(query) except Exception as e: status = False logging.info("handler name - %r, message_name - %r, info - %r, error - %r", "AddCommentHandler", "ADD_COMMENT", "FAIL", e) return Response(body={ "MESSAGE_NAME": "ADD_COMMENT", "STATUS": status })
async def post(self) -> Response: """Uploads a file to storage Request ------ should be contain multipart data ------ Response ------ <file_hash> str: new file name generated by hash function """ if not self.request.can_read_body: raise ValidationError if 'multipart' not in self.request.content_type: raise ValidationError( message='Only multipart content is supported') reader = await self.request.multipart() file_manager = self._create_file_manager() try: async for file_stream in reader: if file_stream.filename: file_hash = await file_manager.save_file(file_stream) break response = Response(body={'file_hash': file_hash}, headers={'Location': f'/files/{file_hash}'}, status=HTTPStatus.CREATED) return response except EmptyFileError as e: logger.exception(e) raise ValidationError(message='File is empty') from e
async def get(self): await self.check_import_exists() # В задании требуется, чтобы ключами были номера месяцев # (без ведущих нулей, "01" -> 1). month = func.date_part('month', citizens_t.c.birth_date) month = cast(month, Integer).label('month') query = select([ month, relations_t.c.citizen_id, func.count(relations_t.c.relative_id).label('presents') ]).select_from( relations_t.join( citizens_t, and_( citizens_t.c.import_id == relations_t.c.import_id, citizens_t.c.citizen_id == relations_t.c.relative_id ) ) ).group_by( month, relations_t.c.import_id, relations_t.c.citizen_id ).where( relations_t.c.import_id == self.import_id ) rows = await self.pg.fetch(query) result = {i: [] for i in range(1, 13)} for month, rows in groupby(rows, key=lambda row: row['month']): for row in rows: result[month].append({'citizen_id': row['citizen_id'], 'presents': row['presents']}) return Response(body={'data': result})
async def post(self, request): data = await request.json() group, _created = get_or_create(session, DomainGroup, name=data['name']) domains = [] if data.get('domains'): for domain_el in data.get('domains'): domain, _domain_created = get_or_create(session, Domain, domain=domain_el) domains.append({ 'id': domain.id, 'domain': domain_el, 'created': _domain_created }) return Response(status=200, body=self.resource.encode({ 'id': group.id, 'name': group.name, 'domains': domains, 'created': _created }), content_type='application/json')
async def avatar(request): # process the input try: token = bytes(request.match_info['token'], 'utf8') data = request.app['fernet'].decrypt(token) except InvalidToken: raise web.HTTPNotFound data = json.loads(data) email = data['email'] size = data.get('size', 128) fallback = data.get('fallback', None) url = await get_url(email, size) # fetch the avatar, and send it off async with request.app['client_session'].get(url) as resp: if resp.status == 404: if fallback: raise web.HTTPFound(fallback) else: raise web.HTTPNotFound data = await resp.read() return Response(body=data, content_type=resp.content_type)
async def index(request: Request): try: return Response(body=json.dumps({"host": socket.gethostname()}), headers={'content-type': 'application/json'}) except Exception as ex: log.warning(f"Endpoint: /, Method: get. Error:{str(ex)}") return HTTPInternalServerError()
def content_handler(self, path): """Serve config.repo and public.key.""" if path == self.repository_config_file_name: base_url = f"{settings.CONTENT_ORIGIN}{settings.CONTENT_PATH_PREFIX}{self.base_path}/" publication = self.publication.cast() val = textwrap.dedent(f"""\ [{self.name}] enabled=1 baseurl={base_url} gpgcheck={publication.gpgcheck} repo_gpgcheck={publication.repo_gpgcheck} """) repository_pk = self.publication.repository.pk repository = RpmRepository.objects.get(pk=repository_pk) signing_service = repository.metadata_signing_service if signing_service: gpgkey_path = urllib.parse.urljoin( settings.CONTENT_ORIGIN, settings.CONTENT_PATH_PREFIX) gpgkey_path = urllib.parse.urljoin(gpgkey_path, self.base_path, True) gpgkey_path += "/repodata/public.key" val += f"gpgkey={gpgkey_path}\n" return Response(body=val)
def response( # pylint: disable=unused-argument req: Request, code: int, text: str = None, encoding: str = None) -> Response: """ Formats an aiohttp Response. :param req: The original aiohttp Request. :type req: :class:`aiohttp.web_request.Request` :param code: The HTTP result code to return. :type code: int :param text: The text to return. :type text: str :param encoding: The text encoding. Defaults to UTF-8. :type encoding: str :return: The aoihttp Response :rtype: :class:`aiohttp.web_response.Response` """ response = Response(status=code) if text: response.content_type = "text/plain" response.body = text.encode( encoding=encoding if encoding else "utf-8") return response