Python aiohttp.web.Request() Examples

The following are 30 code examples of aiohttp.web.Request(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module aiohttp.web , or try the search function .
Example #1
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

    inbound_activity: Activity = Activity().deserialize(body)

    current_conversation_id = inbound_activity.conversation.id
    current_service_url = inbound_activity.service_url

    next_conversation_id = FACTORY.create_skill_conversation_id(current_conversation_id, current_service_url)

    await CLIENT.post_activity(CONFIG.APP_ID, CONFIG.SKILL_APP_ID, TO_URI, SERVICE_URL, next_conversation_id, inbound_activity)
    return Response(status=201) 
Example #2
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""

    try:
        response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        if response:
            return json_response(data=response.body, status=response.status)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #3
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""

    try:
        response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        if response:
            return json_response(data=response.body, status=response.status)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #4
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""

    try:
        invoke_response = await ADAPTER.process_activity(
            activity, auth_header, BOT.on_turn
        )
        if invoke_response:
            return json_response(
                data=invoke_response.body, status=invoke_response.status
            )
        return Response(status=201)
    except PermissionError:
        return Response(status=401)
    except Exception:
        return Response(status=500) 
Example #5
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""

    try:
        invoke_response = await ADAPTER.process_activity(
            activity, auth_header, BOT.on_turn
        )
        if invoke_response:
            return json_response(
                data=invoke_response.body, status=invoke_response.status
            )
        return Response(status=201)
    except PermissionError:
        return Response(status=401)
    except Exception:
        return Response(status=500) 
Example #6
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""

    try:
        response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        if response:
            return json_response(data=response.body, status=response.status)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #7
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""

    try:
        response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        if response:
            return json_response(data=response.body, status=response.status)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #8
Source File: client_auth.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def login(request: web.Request) -> web.Response:
    info, err = await read_client_auth_request(request)
    if err is not None:
        return err
    api, _, username, password, _ = info
    device_id = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8))
    try:
        return web.json_response(await api.request(Method.POST, Path.login, content={
            "type": "m.login.password",
            "identifier": {
                "type": "m.id.user",
                "user": username,
            },
            "password": password,
            "device_id": f"maubot_{device_id}",
        }))
    except MatrixRequestError as e:
        return web.json_response({
            "errcode": e.errcode,
            "error": e.message,
        }, status=e.http_status) 
Example #9
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages(req: Request) -> Response:
    # Create the Bot
    bot = AuthBot(CONVERSATION_STATE, USER_STATE, DIALOG)

    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""

    try:
        await ADAPTER.process_activity(activity, auth_header, bot.on_turn)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #10
Source File: client_auth.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def read_client_auth_request(request: web.Request) -> Tuple[Optional[AuthRequestInfo],
                                                                  Optional[web.Response]]:
    server_name = request.match_info.get("server", None)
    server = registration_secrets().get(server_name, None)
    if not server:
        return None, resp.server_not_found
    try:
        body = await request.json()
    except JSONDecodeError:
        return None, resp.body_not_json
    try:
        username = body["username"]
        password = body["password"]
    except KeyError:
        return None, resp.username_or_password_missing
    try:
        base_url = server["url"]
        secret = server["secret"]
    except KeyError:
        return None, resp.invalid_server
    api = HTTPAPI(base_url, "", loop=get_loop())
    user_type = body.get("user_type", "bot")
    return AuthRequestInfo(api, secret, username, password, user_type), None 
Example #11
Source File: client_auth.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def register(request: web.Request) -> web.Response:
    info, err = await read_client_auth_request(request)
    if err is not None:
        return err
    api, secret, username, password, user_type = info
    res = await api.request(Method.GET, Path.admin.register)
    nonce = res["nonce"]
    mac = generate_mac(secret, nonce, username, password, user_type=user_type)
    try:
        return web.json_response(await api.request(Method.POST, Path.admin.register, content={
            "nonce": nonce,
            "username": username,
            "password": password,
            "admin": False,
            "mac": mac,
            # Older versions of synapse will ignore this field if it is None
            "user_type": user_type,
        }))
    except MatrixRequestError as e:
        return web.json_response({
            "errcode": e.errcode,
            "error": e.message,
            "http_status": e.http_status,
        }, status=HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #12
Source File: decorated_functions_service.py    From tomodachi with MIT License 5 votes vote down vote up
def count_3(self, request: web.Request) -> str:
        return str(self.invocation_count) 
Example #13
Source File: http_access_log_service.py    From tomodachi with MIT License 5 votes vote down vote up
def test_ignore_one(self, request: web.Request) -> tomodachi.HttpResponse:
        test = await request.text()
        if test == '200':
            return tomodachi.HttpResponse(body='test-200', status=200)
        else:
            return tomodachi.HttpResponse(body='test-201', status=201) 
Example #14
Source File: decorated_functions_service.py    From tomodachi with MIT License 5 votes vote down vote up
def count_4(self, request: web.Request) -> str:
        return str(self.invocation_count) 
Example #15
Source File: server.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def log(self, request: web.Request, response: web.Response, time: int):
        self.logger.info(f'{request.remote} "{request.method} {request.path} '
                         f'{response.status} {response.body_length} '
                         f'in {round(time, 4)}s"') 
Example #16
Source File: server.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def handle_plugin_path(self, request: web.Request) -> web.Response:
        for path, app in self.plugin_routes.items():
            if request.path.startswith(path):
                request = request.clone(rel_url=request.rel_url
                                        .with_path(request.rel_url.path[len(path):])
                                        .with_query(request.query_string))
                return await app.handle(request)
        return web.Response(status=404) 
Example #17
Source File: server.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def setup_management_ui(self) -> None:
        ui_base = self.config["server.ui_base_path"]
        if ui_base == "/":
            ui_base = ""
        directory = (self.config["server.override_resource_path"]
                     or pkg_resources.resource_filename("maubot", "management/frontend/build"))
        self.app.router.add_static(f"{ui_base}/static", f"{directory}/static")
        self.setup_static_root_files(directory, ui_base)

        with open(f"{directory}/index.html", "r") as file:
            index_html = file.read()

        @web.middleware
        async def frontend_404_middleware(request: web.Request, handler) -> web.Response:
            if hasattr(handler, "__self__") and isinstance(handler.__self__, web.StaticResource):
                try:
                    return await handler(request)
                except web.HTTPNotFound:
                    return web.Response(body=index_html, content_type="text/html")
            return await handler(request)

        async def ui_base_redirect(_: web.Request) -> web.Response:
            raise web.HTTPFound(f"{ui_base}/")

        self.app.middlewares.append(frontend_404_middleware)
        self.app.router.add_get(f"{ui_base}/", lambda _: web.Response(body=index_html,
                                                                      content_type="text/html"))
        self.app.router.add_get(ui_base, ui_base_redirect) 
Example #18
Source File: client.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_clients(_: web.Request) -> web.Response:
    return resp.found([client.to_dict() for client in Client.cache.values()]) 
Example #19
Source File: client.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_client(request: web.Request) -> web.Response:
    user_id = request.match_info.get("id", None)
    client = Client.get(user_id, None)
    if not client:
        return resp.client_not_found
    return resp.found(client.to_dict()) 
Example #20
Source File: decorated_functions_service.py    From tomodachi with MIT License 5 votes vote down vote up
def count_2(self, request: web.Request) -> str:
        return str(self.invocation_count) 
Example #21
Source File: decorated_functions_service.py    From tomodachi with MIT License 5 votes vote down vote up
def count_1(self, request: web.Request) -> str:
        return str(self.invocation_count) 
Example #22
Source File: start_process_service_http_1.py    From tomodachi with MIT License 5 votes vote down vote up
def index(self, request: web.Request) -> str:
        self.function_order.append('index')
        return 'response' 
Example #23
Source File: http_access_log_service.py    From tomodachi with MIT License 5 votes vote down vote up
def test_404(self, request: web.Request) -> str:
        return 'test 404' 
Example #24
Source File: client_proxy.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def proxy(request: web.Request) -> web.StreamResponse:
    user_id = request.match_info.get("id", None)
    client = Client.get(user_id, None)
    if not client:
        return resp.client_not_found

    path = request.match_info.get("path", None)
    query = request.query.copy()
    try:
        del query["access_token"]
    except KeyError:
        pass
    headers = request.headers.copy()
    del headers["Host"]
    headers["Authorization"] = f"Bearer {client.access_token}"
    if "X-Forwarded-For" not in headers:
        peer = request.transport.get_extra_info("peername")
        if peer is not None:
            host, port = peer
            headers["X-Forwarded-For"] = f"{host}:{port}"

    data = await request.read()
    async with http.request(request.method, f"{client.homeserver}/{path}", headers=headers,
                            params=query, data=data) as proxy_resp:
        response = web.StreamResponse(status=proxy_resp.status, headers=proxy_resp.headers)
        await response.prepare(request)
        async for chunk in proxy_resp.content.iter_chunked(PROXY_CHUNK_SIZE):
            await response.write(chunk)
        await response.write_eof()
        return response 
Example #25
Source File: http_access_log_service.py    From tomodachi with MIT License 5 votes vote down vote up
def test_ignore_all(self, request: web.Request) -> str:
        return 'test' 
Example #26
Source File: http_access_log_service.py    From tomodachi with MIT License 5 votes vote down vote up
def test(self, request: web.Request) -> str:
        return 'test' 
Example #27
Source File: http_service_same_port.py    From tomodachi with MIT License 5 votes vote down vote up
def test(self, request: web.Request) -> str:
        return 'test' 
Example #28
Source File: http_service.py    From tomodachi with MIT License 5 votes vote down vote up
def websocket_with_header(self, websocket: web.WebSocketResponse, request: web.Request) -> None:
        self.websocket_header = request.headers.get('User-Agent') 
Example #29
Source File: http_service.py    From tomodachi with MIT License 5 votes vote down vote up
def test_404(self, request: web.Request) -> str:
        return 'test 404' 
Example #30
Source File: http_service.py    From tomodachi with MIT License 5 votes vote down vote up
def authorization(self, request: web.Request) -> str:
        return request._cache.get('auth').login if request._cache.get('auth') else ''