def _get_response(exc, content, status_code, headers={}):
        from aiohttp.web_response import Response

        resp = Response(status=status_code, text=content)
        for header_name, header_value in convert_to_str(headers.items()):
            resp.headers[header_name] = header_value
        return resp
Exemplo n.º 2
0
    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
Exemplo n.º 3
0
 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")
Exemplo n.º 4
0
    def handle_error(self, request, status=500, exc=None, message=None):
        """Handle errors.

        Returns HTTP response with specific status code. Logs additional
        information. It always closes current connection."""
        self.log_exception("Error handling request", exc_info=exc)

        if status == 500:
            msg = "<h1>500 Internal Server Error</h1>"
            if self.debug:
                try:
                    tb = traceback.format_exc()
                    tb = html_escape(tb)
                    msg += '<br><h2>Traceback:</h2>\n<pre>'
                    msg += tb
                    msg += '</pre>'
                except:  # pragma: no cover
                    pass
            else:
                msg += "Server got itself in trouble"
                msg = ("<html><head><title>500 Internal Server Error</title>"
                       "</head><body>" + msg + "</body></html>")
        else:
            msg = message

        resp = Response(status=status, text=msg, content_type='text/html')
        resp.force_close()

        # some data already got sent, connection is broken
        if request.writer.output_size > 0 or self.transport is None:
            self.force_close()

        return resp
Exemplo n.º 5
0
    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)
Exemplo n.º 6
0
    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"
                }
            })
Exemplo n.º 7
0
    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 ошибка"
                    }
                })
Exemplo n.º 8
0
async def authorize(request, response: Response,
                    vk_access_token: VkOAuthAccessTokenDTO):
    """Авторизация пользователя"""
    store: VKAccessTokenObjectManager = request.app.stores.access_tokens
    auth_token = await store.set_access_token(vk_access_token)
    response.set_cookie(name=AUTH_COOKIE_NAME,
                        value=auth_token,
                        expires=vk_access_token.expires_in)
    return response
Exemplo n.º 9
0
 def __init__(self, data=None):
     if data is None:
         data = self.default_msg
     data = json.dumps(data)
     Response.__init__(self,
                       text=data,
                       status=self.status,
                       content_type='application/json')
     Exception.__init__(self)
Exemplo n.º 10
0
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='')
Exemplo n.º 11
0
    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))
Exemplo n.º 12
0
 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))
Exemplo n.º 13
0
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)
Exemplo n.º 14
0
 def __init__(self, body=irc['INTERNAL_SERVER_ERROR'], status=500):
     Response.__init__(
         self,
         status=status,
         headers=None,
         reason=None,
         text=None,
         content_type='application/json',
         body=json.dumps({"errors": body}),
     )
Exemplo n.º 15
0
    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
Exemplo n.º 16
0
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)
Exemplo n.º 17
0
def logout(
    request,
    response: Response,
):
    """Деавторизация пользователя."""
    auth_cookie: Optional[str] = request.cookies.get(AUTH_COOKIE_NAME, None)
    if auth_cookie:
        store: VKAccessTokenObjectManager = request.app.stores.access_tokens
        asyncio.get_event_loop().create_task(
            store.delete_access_token(auth_cookie))
        response.del_cookie(name=AUTH_COOKIE_NAME)
    return response
Exemplo n.º 18
0
 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')
Exemplo n.º 19
0
    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))
Exemplo n.º 20
0
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)
Exemplo n.º 21
0
 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))
Exemplo n.º 22
0
    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)
Exemplo n.º 23
0
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)
Exemplo n.º 24
0
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)
Exemplo n.º 25
0
    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
Exemplo n.º 26
0
    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
        })
Exemplo n.º 27
0
    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'})
Exemplo n.º 28
0
    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})
Exemplo n.º 29
0
    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
Exemplo n.º 30
0
    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')