Python aiohttp.web.View() Examples

The following are 26 code examples of aiohttp.web.View(). 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: test_aiohttp.py    From aiojobs with Apache License 2.0 6 votes vote down vote up
def test_atomic_from_view(aiohttp_client):
    app = web.Application()

    class MyView(web.View):
        @atomic
        async def get(self):
            return web.Response()

    app.router.add_route("*", "/", MyView)
    aiojobs_setup(app)

    client = await aiohttp_client(app)
    resp = await client.get('/')
    assert resp.status == 200

    scheduler = get_scheduler_from_app(app)

    assert scheduler.active_count == 0
    assert scheduler.pending_count == 0 
Example #2
Source File: test_aiohttp.py    From aiojobs with Apache License 2.0 6 votes vote down vote up
def test_nested_application(aiohttp_client):
    app = web.Application()
    aiojobs_setup(app)

    app2 = web.Application()

    class MyView(web.View):
        async def get(self):
            assert get_scheduler_from_request(self.request) ==\
                get_scheduler_from_app(app)
            return web.Response()

    app2.router.add_route("*", "/", MyView)
    app.add_subapp("/sub/", app2)

    client = await aiohttp_client(app)
    resp = await client.get("/sub/")
    assert resp.status == 200 
Example #3
Source File: test_aiohttp.py    From aiojobs with Apache License 2.0 6 votes vote down vote up
def test_nested_application_separate_scheduler(aiohttp_client):
    app = web.Application()
    aiojobs_setup(app)

    app2 = web.Application()
    aiojobs_setup(app2)

    class MyView(web.View):
        async def get(self):
            assert get_scheduler_from_request(self.request) !=\
                get_scheduler_from_app(app)
            assert get_scheduler_from_request(self.request) ==\
                get_scheduler_from_app(app2)
            return web.Response()

    app2.router.add_route("*", "/", MyView)
    app.add_subapp("/sub/", app2)

    client = await aiohttp_client(app)
    resp = await client.get("/sub/")
    assert resp.status == 200 
Example #4
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_render_class_based_view(aiohttp_client):
    class MyView(web.View):
        @aiohttp_jinja2.template('tmpl.jinja2')
        async def get(self):
            return {'head': 'HEAD', 'text': 'text'}

    template = '<html><body><h1>{{head}}</h1>{{text}}</body></html>'

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({
        'tmpl.jinja2': template
    }))

    app.router.add_route('*', '/', MyView)

    client = await aiohttp_client(app)

    resp = await client.get('/')

    assert 200 == resp.status
    txt = await resp.text()
    assert '<html><body><h1>HEAD</h1>text</body></html>' == txt 
Example #5
Source File: test_mixin.py    From aiohttp-cors with Apache License 2.0 5 votes vote down vote up
def test_method_with_custom_cors(app):
    """Test adding resource with web.View as handler"""
    request = mock.Mock()
    request.app = app
    view = CustomMethodView(request)

    assert hasattr(view.post, 'post_cors_config')
    assert asyncio.iscoroutinefunction(view.post)
    config = view.get_request_config(request, 'post')

    assert config.get('www.client1.com') == CUSTOM_CONFIG['www.client1.com'] 
Example #6
Source File: aiohttp_apispec.py    From aiohttp-apispec with MIT License 5 votes vote down vote up
def _register(self, app: web.Application):
        for route in app.router.routes():
            if issubclass_py37fix(route.handler, web.View) and route.method == METH_ANY:
                for attr in dir(route.handler):
                    if attr.upper() in METH_ALL:
                        view = getattr(route.handler, attr)
                        method = attr
                        self._register_route(route, method, view)
            else:
                method = route.method.lower()
                view = route.handler
                self._register_route(route, method, view)
        app["swagger_dict"] = self.swagger_dict() 
Example #7
Source File: middlewares.py    From aiohttp-apispec with MIT License 5 votes vote down vote up
def validation_middleware(request: web.Request, handler) -> web.Response:
    """
    Validation middleware for aiohttp web app

    Usage:

    .. code-block:: python

        app.middlewares.append(validation_middleware)


    """
    orig_handler = request.match_info.handler
    if not hasattr(orig_handler, "__schemas__"):
        if not issubclass_py37fix(orig_handler, web.View):
            return await handler(request)
        sub_handler = getattr(orig_handler, request.method.lower(), None)
        if sub_handler is None:
            return await handler(request)
        if not hasattr(sub_handler, "__schemas__"):
            return await handler(request)
        schemas = sub_handler.__schemas__
    else:
        schemas = orig_handler.__schemas__
    result = {}
    for schema in schemas:
        data = await request.app["_apispec_parser"].parse(
            schema["schema"], request, locations=schema["locations"]
        )
        if schema["put_into"]:
            request[schema["put_into"]] = data
        elif data:
            try:
                result.update(data)
            except (ValueError, TypeError):
                result = data
                break
    request[request.app["_apispec_request_data_name"]] = result
    return await handler(request) 
Example #8
Source File: test_permissions.py    From aiohttp-jwt with MIT License 5 votes vote down vote up
def test_check_permissions_class(
        create_app, fake_payload, aiohttp_client, secret):
    token = jwt.encode({**fake_payload, 'scopes': ['view']}, secret)

    class View:
        @check_permissions(['view'])
        async def handler(self, request):
            return web.json_response({})
    routes = (('/foo', View().handler),)
    client = await aiohttp_client(
        create_app(routes, credentials_required=False))
    response = await client.get('/foo', headers={
        'Authorization': 'Bearer {}'.format(token.decode('utf-8'))
    })
    assert response.status == 200 
Example #9
Source File: test_permissions.py    From aiohttp-jwt with MIT License 5 votes vote down vote up
def test_login_required_view(
        create_app, fake_payload, aiohttp_client, secret):
    class App(web.View):
        @login_required
        async def get(self):
            return web.json_response({})

    views = (('/foo', App),)
    client = await aiohttp_client(
        create_app(views=views, credentials_required=False))

    response = await client.get('/foo')
    assert response.status == 401
    assert 'Authorization required' in response.reason 
Example #10
Source File: test_permissions.py    From aiohttp-jwt with MIT License 5 votes vote down vote up
def test_login_required_class(
        create_app, fake_payload, aiohttp_client, secret):
    class View:
        @login_required
        async def handler(self, request):
            return web.json_response({})

    routes = (('/foo', View().handler),)
    client = await aiohttp_client(
        create_app(routes, credentials_required=False))
    response = await client.get('/foo')
    assert response.status == 401
    assert 'Authorization required' in response.reason 
Example #11
Source File: permissions.py    From aiohttp-jwt with MIT License 5 votes vote down vote up
def login_required(func):
    @wraps(func)
    async def wrapped(*args, **kwargs):
        if middleware._request_property is ...:
            raise RuntimeError('Incorrect usage of decorator.'
                               'Please initialize middleware first')
        request = args[-1]

        if isinstance(request, web.View):
            request = request.request

        if not isinstance(request, web.BaseRequest):  # pragma: no cover
            raise RuntimeError(
                'Incorrect usage of decorator.'
                'Expect web.BaseRequest as an argument')

        if not request.get(middleware._request_property):
            raise web.HTTPUnauthorized(reason='Authorization required')

        return await func(*args, **kwargs)
    return wrapped 
Example #12
Source File: urldispatcher_router_adapter.py    From aiohttp-cors with Apache License 2.0 5 votes vote down vote up
def _is_web_view(entity, strict=True):
    webview = False
    if isinstance(entity, web.AbstractRoute):
        handler = entity.handler
        if isinstance(handler, type) and issubclass(handler, web.View):
            webview = True
            if not issubclass(handler, CorsViewMixin):
                if strict:
                    raise ValueError("web view should be derived from "
                                     "aiohttp_cors.CorsViewMixin for working "
                                     "with the library")
                else:
                    return False
    return webview 
Example #13
Source File: test_cors_config.py    From aiohttp-cors with Apache License 2.0 5 votes vote down vote up
def test_disable_bare_view(app, cors):
    class View(web.View):
        pass

    route = app.router.add_route("*", "/", View)
    with pytest.raises(ValueError):
        cors.add(route) 
Example #14
Source File: test_cors_config.py    From aiohttp-cors with Apache License 2.0 5 votes vote down vote up
def test_web_view_warning(app, cors):
    """Test adding resource with web.View as handler"""
    route = app.router.add_route("*", "/", _View)
    with pytest.warns(DeprecationWarning):
        cors.add(route, webview=True) 
Example #15
Source File: test_mixin.py    From aiohttp-cors with Apache License 2.0 5 votes vote down vote up
def test_method_with_default_config(app):
    """Test adding resource with web.View as handler"""
    request = mock.Mock()
    request.app = app
    view = SimpleView(request)

    assert not hasattr(view.get, 'get_cors_config')
    config = view.get_request_config(request, 'get')

    assert config.get('*') == DEFAULT_CONFIG['*'] 
Example #16
Source File: test_mixin.py    From aiohttp-cors with Apache License 2.0 5 votes vote down vote up
def test_method_with_class_config(app):
    """Test adding resource with web.View as handler"""
    request = mock.Mock()
    request.app = app
    view = SimpleViewWithConfig(request)

    assert not hasattr(view.get, 'get_cors_config')
    config = view.get_request_config(request, 'get')

    assert config.get('*') == CLASS_CONFIG['*'] 
Example #17
Source File: test_main.py    From aiohttp-cors with Apache License 2.0 5 votes vote down vote up
def test_preflight_request_mult_routes_with_one_options_webview(
        aiohttp_client):
    """Test CORS preflight handling on resource that is available through
    several routes.
    """
    app = web.Application()
    cors = _setup(app, defaults={
        "*": ResourceOptions(
            allow_credentials=True,
            expose_headers="*",
            allow_headers="*",
        )
    })

    class TestView(web.View, CorsViewMixin):
        async def get(self):
            resp = web.Response(text=TEST_BODY)

            resp.headers[SERVER_CUSTOM_HEADER_NAME] = \
                SERVER_CUSTOM_HEADER_VALUE

            return resp

        put = get

    cors.add(app.router.add_route("*", "/{name}", TestView))

    client = await aiohttp_client(app)

    resp = await client.options(
        "/user",
        headers={
            hdrs.ORIGIN: "http://example.org",
            hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT"
        }
    )
    assert resp.status == 200

    data = await resp.text()
    assert data == "" 
Example #18
Source File: test_main.py    From aiohttp-cors with Apache License 2.0 5 votes vote down vote up
def test_preflight_request_max_age_webview(aiohttp_client):
    """Test CORS preflight handling on resource that is available through
    several routes.
    """
    app = web.Application()
    cors = _setup(app, defaults={
        "*": ResourceOptions(
            allow_credentials=True,
            expose_headers="*",
            allow_headers="*",
            max_age=1200
        )
    })

    class TestView(web.View, CorsViewMixin):
        async def get(self):
            resp = web.Response(text=TEST_BODY)

            resp.headers[SERVER_CUSTOM_HEADER_NAME] = \
                SERVER_CUSTOM_HEADER_VALUE

            return resp

    cors.add(app.router.add_route("*", "/{name}", TestView))

    client = await aiohttp_client(app)

    resp = await client.options(
        "/user",
        headers={
            hdrs.ORIGIN: "http://example.org",
            hdrs.ACCESS_CONTROL_REQUEST_METHOD: "GET"
        }
    )
    assert resp.status == 200
    assert resp.headers[hdrs.ACCESS_CONTROL_MAX_AGE].upper() == "1200"

    data = await resp.text()
    assert data == "" 
Example #19
Source File: swagger.py    From aiohttp-swagger3 with Apache License 2.0 5 votes vote down vote up
def _handle_swagger_method_call(
        self, view: web.View, route: "SwaggerRoute"
    ) -> web.StreamResponse:
        kwargs = await route.parse(view.request)
        return await route.handler(view, **kwargs) 
Example #20
Source File: test_class_based_view.py    From aiohttp-swagger3 with Apache License 2.0 5 votes vote down vote up
def test_class_based_spec_file(swagger_file, aiohttp_client):
    class Pets(web.View):
        async def get(self, limit: Optional[int] = None):
            pets = []
            for i in range(limit or 3):
                pets.append({"id": i, "name": f"pet_{i}", "tag": f"tag_{i}"})
            return web.json_response(pets)

        async def post(self, body: Dict):
            return web.json_response(body, status=201)

    swagger = swagger_file()
    swagger.add_routes([web.view("/pets", Pets)])

    client = await aiohttp_client(swagger._app)

    resp = await client.get("/pets", params={"limit": 1})
    assert resp.status == 200
    assert await resp.json() == [{"id": 0, "name": "pet_0", "tag": "tag_0"}]

    resp = await client.get("/pets")
    assert resp.status == 200
    assert await resp.json() == [
        {"id": 0, "name": "pet_0", "tag": "tag_0"},
        {"id": 1, "name": "pet_1", "tag": "tag_1"},
        {"id": 2, "name": "pet_2", "tag": "tag_2"},
    ]

    req = {"id": 10, "name": "pet", "tag": "tag"}
    resp = await client.post("/pets", json=req)
    assert resp.status == 201
    assert await resp.json() == req 
Example #21
Source File: main.py    From aiohttp-swagger3 with Apache License 2.0 5 votes vote down vote up
def main():
    app = web.Application()
    s = SwaggerDocs(app, swagger_ui_settings=SwaggerUiSettings(path="/docs"))
    s.add_routes([web.view("/r/{param_id}", View)])
    web.run_app(app) 
Example #22
Source File: aiohttp.py    From aiojobs with Apache License 2.0 5 votes vote down vote up
def atomic(coro):
    @wraps(coro)
    async def wrapper(request):
        if isinstance(request, View):
            # Class Based View decorated.
            request = request.request

        job = await spawn(request, coro(request))
        return await job.wait()
    return wrapper 
Example #23
Source File: test_aiohttp.py    From aiojobs with Apache License 2.0 5 votes vote down vote up
def test_nested_application_not_set(aiohttp_client):
    app = web.Application()
    app2 = web.Application()

    class MyView(web.View):
        async def get(self):
            assert get_scheduler_from_request(self.request) is None
            return web.Response()

    app2.router.add_route("*", "/", MyView)
    app.add_subapp("/sub/", app2)

    client = await aiohttp_client(app)
    resp = await client.get("/sub/")
    assert resp.status == 200 
Example #24
Source File: __init__.py    From aiohttp-jinja2 with Apache License 2.0 5 votes vote down vote up
def template(
    template_name: str,
    *,
    app_key: str = APP_KEY,
    encoding: str = 'utf-8',
    status: int = 200
) -> Any:

    def wrapper(func: Any) -> Any:
        @functools.wraps(func)
        async def wrapped(*args: Any) -> web.StreamResponse:
            if asyncio.iscoroutinefunction(func):
                coro = func
            else:
                warnings.warn("Bare functions are deprecated, "
                              "use async ones", DeprecationWarning)
                coro = asyncio.coroutine(func)
            context = await coro(*args)
            if isinstance(context, web.StreamResponse):
                return context

            # Supports class based views see web.View
            if isinstance(args[0], AbstractView):
                request = args[0].request
            else:
                request = args[-1]

            response = render_template(template_name, request, context,
                                       app_key=app_key, encoding=encoding)
            response.set_status(status)
            return response
        return wrapped
    return wrapper 
Example #25
Source File: test_methods.py    From aiohttp-swagger3 with Apache License 2.0 4 votes vote down vote up
def test_all_methods(swagger_docs, aiohttp_client):
    class View(web.View):
        async def get(self):
            """
            ---

            responses:
              '200':
                description: OK.

            """
            return web.json_response()

    async def handler(request):
        """
        ---

        responses:
          '200':
            description: OK.

        """
        return web.json_response()

    swagger = swagger_docs()
    swagger.add_get("/r", handler, allow_head=False),
    swagger.add_head("/r", handler),
    swagger.add_put("/r", handler),
    swagger.add_patch("/r", handler),
    swagger.add_post("/r", handler),
    swagger.add_delete("/r", handler),
    swagger.add_options("/r", handler),
    swagger.add_view("/r2", View),

    client = await aiohttp_client(swagger._app)

    for method in (
        hdrs.METH_GET,
        hdrs.METH_HEAD,
        hdrs.METH_POST,
        hdrs.METH_PUT,
        hdrs.METH_PATCH,
        hdrs.METH_DELETE,
        hdrs.METH_OPTIONS,
    ):
        resp = await getattr(client, method.lower())("/r")
        assert resp.status == 200

    resp = await client.get("/r2")
    assert resp.status == 200 
Example #26
Source File: permissions.py    From aiohttp-jwt with MIT License 4 votes vote down vote up
def check_permissions(
    scopes,
    permissions_property='scopes',
    comparison=match_all,
):
    if not callable(comparison):
        raise TypeError('comparison should be a func')

    if isinstance(scopes, str):
        scopes = scopes.split(' ')

    def scopes_checker(func):
        @wraps(func)
        async def wrapped(*args, **kwargs):
            if middleware._request_property is ...:
                raise RuntimeError('Incorrect usage of decorator.'
                                   'Please initialize middleware first')

            request = args[-1]

            if isinstance(request, web.View):
                request = request.request

            if not isinstance(request, web.BaseRequest):  # pragma: no cover
                raise RuntimeError(
                    'Incorrect usage of decorator.'
                    'Expect web.BaseRequest as an argument')

            payload = request.get(middleware._request_property)

            if not payload:
                raise web.HTTPUnauthorized(reason='Authorization required')

            user_scopes = payload.get(permissions_property, [])

            if not isinstance(user_scopes, collections.Iterable):
                raise web.HTTPForbidden(reason='Invalid permissions format')

            if not comparison(scopes, user_scopes):
                raise web.HTTPForbidden(reason='Insufficient scopes')

            return await func(*args, **kwargs)
        return wrapped

    return scopes_checker