Python aiohttp.web.Response() Examples

The following are 30 code examples of aiohttp.web.Response(). 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: hello_srv.py    From hsds with Apache License 2.0 6 votes vote down vote up
def hello(request):
    name = request.match_info.get("name", "foo")
    n = datetime.now().isoformat()
    delay = random.randint(0, 3)
    await asyncio.sleep(delay)
    headers = {"content_type": "text/html", "delay": str(delay)}
    # opening file is not async here, so it may block, to improve
    # efficiency of this you can consider using asyncio Executors
    # that will delegate file operation to separate thread or process
    # and improve performance
    # https://docs.python.org/3/library/asyncio-eventloop.html#executor
    # https://pymotw.com/3/asyncio/executors.html
    with open("html_text.html", "rb") as html_body:
        print("{}: {} delay: {}".format(n, request.path, delay))
        response = web.Response(body=html_body.read(), headers=headers)
    return response 
Example #2
Source File: client.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def _update_client(client: Client, data: dict) -> web.Response:
    try:
        await client.update_access_details(data.get("access_token", None),
                                           data.get("homeserver", None))
    except MatrixInvalidToken:
        return resp.bad_client_access_token
    except MatrixRequestError:
        return resp.bad_client_access_details
    except MatrixConnectionError:
        return resp.bad_client_connection_details
    except ValueError as e:
        return resp.mxid_mismatch(str(e)[len("MXID mismatch: "):])
    with client.db_instance.edit_mode():
        await client.update_avatar_url(data.get("avatar_url", None))
        await client.update_displayname(data.get("displayname", None))
        await client.update_started(data.get("started", None))
        client.enabled = data.get("enabled", client.enabled)
        client.autojoin = data.get("autojoin", client.autojoin)
        client.online = data.get("online", client.online)
        client.sync = data.get("sync", client.sync)
        return resp.updated(client.to_dict()) 
Example #3
Source File: test_requests.py    From gql with MIT License 6 votes vote down vote up
def test_requests_cannot_connect_twice(event_loop, aiohttp_server):
    async def handler(request):
        return web.Response(text=query1_server_answer, content_type="application/json")

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    def test_code():
        sample_transport = RequestsHTTPTransport(url=url)

        with Client(transport=sample_transport,) as session:

            with pytest.raises(TransportAlreadyConnected):
                session.transport.connect()

    await run_sync_test(event_loop, server, test_code) 
Example #4
Source File: test_requests.py    From gql with MIT License 6 votes vote down vote up
def test_requests_cannot_execute_if_not_connected(event_loop, aiohttp_server):
    async def handler(request):
        return web.Response(text=query1_server_answer, content_type="application/json")

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    def test_code():
        sample_transport = RequestsHTTPTransport(url=url)

        query = gql(query1_str)

        with pytest.raises(TransportClosed):
            sample_transport.execute(query)

    await run_sync_test(event_loop, server, test_code) 
Example #5
Source File: test_aiohttp.py    From gql with MIT License 6 votes vote down vote up
def test_aiohttp_error_code(event_loop, aiohttp_server):
    async def handler(request):
        return web.Response(
            text=query1_server_error_answer, content_type="application/json"
        )

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    sample_transport = AIOHTTPTransport(url=url)

    async with Client(transport=sample_transport,) as session:

        query = gql(query1_str)

        with pytest.raises(TransportQueryError):
            await session.execute(query) 
Example #6
Source File: test_aiohttp.py    From gql with MIT License 6 votes vote down vote up
def test_aiohttp_invalid_protocol(event_loop, aiohttp_server, response):
    async def handler(request):
        return web.Response(text=response, content_type="application/json")

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    sample_transport = AIOHTTPTransport(url=url)

    async with Client(transport=sample_transport,) as session:

        query = gql(query1_str)

        with pytest.raises(TransportProtocolError):
            await session.execute(query) 
Example #7
Source File: test_aiohttp.py    From gql with MIT License 6 votes vote down vote up
def test_aiohttp_subscribe_not_supported(event_loop, aiohttp_server):
    async def handler(request):
        return web.Response(text="does not matter", content_type="application/json")

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    sample_transport = AIOHTTPTransport(url=url)

    async with Client(transport=sample_transport,) as session:

        query = gql(query1_str)

        with pytest.raises(NotImplementedError):
            async for result in session.subscribe(query):
                pass 
Example #8
Source File: test_aiohttp.py    From gql with MIT License 6 votes vote down vote up
def test_aiohttp_cannot_connect_twice(event_loop, aiohttp_server):
    async def handler(request):
        return web.Response(text=query1_server_answer, content_type="application/json")

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    sample_transport = AIOHTTPTransport(url=url, timeout=10)

    async with Client(transport=sample_transport,) as session:

        with pytest.raises(TransportAlreadyConnected):
            await session.transport.connect() 
Example #9
Source File: test_aiohttp.py    From gql with MIT License 6 votes vote down vote up
def test_aiohttp_cannot_execute_if_not_connected(event_loop, aiohttp_server):
    async def handler(request):
        return web.Response(text=query1_server_answer, content_type="application/json")

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    sample_transport = AIOHTTPTransport(url=url, timeout=10)

    query = gql(query1_str)

    with pytest.raises(TransportClosed):
        await sample_transport.execute(query) 
Example #10
Source File: test_requests.py    From gql with MIT License 6 votes vote down vote up
def test_requests_invalid_protocol(event_loop, aiohttp_server, response):
    async def handler(request):
        return web.Response(text=response, content_type="application/json")

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    def test_code():
        sample_transport = RequestsHTTPTransport(url=url)

        with Client(transport=sample_transport,) as session:

            query = gql(query1_str)

            with pytest.raises(TransportProtocolError):
                session.execute(query)

    await run_sync_test(event_loop, server, test_code) 
Example #11
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 #12
Source File: config.py    From friendly-telegram with GNU Affero General Public License v3.0 6 votes vote down vote up
def set_config(self, request):
        uid = await self.check_user(request)
        if uid is None:
            return web.Response(status=401)
        data = await request.json()
        mid, key, value = int(data["mid"]), data["key"], data["value"]
        mod = self.client_data[uid][0].modules[mid]
        if value:
            try:
                value = ast.literal_eval(value)
            except (ValueError, SyntaxError):
                pass
            self.client_data[uid][2].setdefault(mod.__module__, {}).setdefault("__config__", {})[key] = value
        else:
            try:
                del self.client_data[uid][2].setdefault(mod.__module__, {}).setdefault("__config__", {})[key]
            except KeyError:
                pass
        self.client_data[uid][0].send_config_one(mod, self.client_data[uid][2], skip_hook=True)
        self.client_data[uid][2].save()
        return web.Response() 
Example #13
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 #14
Source File: test_requests.py    From gql with MIT License 6 votes vote down vote up
def test_requests_error_code(event_loop, aiohttp_server):
    async def handler(request):
        return web.Response(
            text=query1_server_error_answer, content_type="application/json"
        )

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    def test_code():
        sample_transport = RequestsHTTPTransport(url=url)

        with Client(transport=sample_transport,) as session:

            query = gql(query1_str)

            with pytest.raises(TransportQueryError):
                session.execute(query)

    await run_sync_test(event_loop, server, test_code) 
Example #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
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 #25
Source File: base.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def version(_: web.Request) -> web.Response:
    return web.json_response({
        "version": __version__
    }) 
Example #26
Source File: http.py    From tomodachi with MIT License 5 votes vote down vote up
def get_http_response_status(value: Union[str, bytes, Dict, List, Tuple, web.Response, Response, Exception], request: Optional[web.Request] = None, verify_transport: bool = True) -> Optional[int]:
    if isinstance(value, Exception) or isinstance(value, web.HTTPException):
        status_code = int(getattr(value, 'status', 500)) if value is not None else 500
        return status_code
    else:
        response = await resolve_response(value, request=request)
        status_code = int(response.status) if response is not None else 500
        if verify_transport and request is not None and request.transport is None:
            return 499
        else:
            return status_code 
Example #27
Source File: http_service.py    From tomodachi with MIT License 5 votes vote down vote up
def test_aiohttp(self, request: web.Request) -> web.Response:
        return web.Response(body='test aiohttp', status=200, headers={
            'X-Aiohttp': 'test'
        }) 
Example #28
Source File: http_service.py    From tomodachi with MIT License 5 votes vote down vote up
def test_response_object(self, request: web.Request) -> Response:
        return Response(body='test tomodachi response', status=200, headers={
            'X-Tomodachi-Response': 'test'
        }) 
Example #29
Source File: http_service.py    From tomodachi with MIT License 5 votes vote down vote up
def test_weird_content_type(self, request: web.Request) -> web.Response:
        return web.Response(body='test', status=200, headers={
            'Content-Type': 'text/plain; '
        }) 
Example #30
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"')