Python aiohttp_jinja2.render_template() Examples

The following are 30 code examples of aiohttp_jinja2.render_template(). 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_jinja2 , or try the search function .
Example #1
Source File: test_jinja_globals.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_url_param_forbidden_type(aiohttp_client):

    async def index(request):
        with pytest.raises(TypeError,
                           match=(r"argument value should be str or int, "
                                  r"got arg -> \[<class 'bool'>\] True")):
            aiohttp_jinja2.render_template('tmpl.jinja2', request, {})
        return web.Response()

    async def other(request):
        return

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2':
         "{{ url('other', arg=True)}}"}))

    app.router.add_route('GET', '/', index)
    app.router.add_route('GET', '/uid/{arg}', other, name='other')
    client = await aiohttp_client(app)

    resp = await client.get('/')
    assert 200 == resp.status 
Example #2
Source File: frontend.py    From ooi3 with GNU Affero General Public License v3.0 6 votes vote down vote up
def kcv(self, request):
        """适配KanColleViewer或者74EO中进行游戏的页面,提供一个iframe,在iframe中载入游戏FLASH。该页面会检查会话中是否有api_token、
        api_starttime和world_ip三个参数,缺少其中任意一个都不能进行游戏,跳转回登录页面。

        :param request: aiohttp.web.Request
        :return: aiohttp.web.Response or aiohttp.web.HTTPFound
        """
        session = yield from get_session(request)
        token = session.get('api_token', None)
        starttime = session.get('api_starttime', None)
        world_ip = session.get('world_ip', None)
        if token and starttime and world_ip:
            return aiohttp_jinja2.render_template('kcv.html', request, context={})
        else:
            self.clear_session(session)
            return aiohttp.web.HTTPFound('/') 
Example #3
Source File: frontend.py    From ooi3 with GNU Affero General Public License v3.0 6 votes vote down vote up
def normal(self, request):
        """适配浏览器中进行游戏的页面,该页面会检查会话中是否有api_token、api_starttime和world_ip三个参数,缺少其中任意一个都不能进行
        游戏,跳转回登录页面。

        :param request: aiohttp.web.Request
        :return: aiohttp.web.Response or aiohttp.web.HTTPFound
        """
        session = yield from get_session(request)
        token = session.get('api_token', None)
        starttime = session.get('api_starttime', None)
        world_ip = session.get('world_ip', None)
        if token and starttime and world_ip:
            context = {'scheme': request.scheme,
                       'host': request.host,
                       'token': token,
                       'starttime': starttime}
            return aiohttp_jinja2.render_template('normal.html', request, context)
        else:
            self.clear_session(session)
            return aiohttp.web.HTTPFound('/') 
Example #4
Source File: frontend.py    From ooi3 with GNU Affero General Public License v3.0 6 votes vote down vote up
def flash(self, request):
        """适配KanColleViewer或者74EO中进行游戏的页面,展示,该页面会检查会话中是否有api_token、api_starttime和world_ip三个参数,
        缺少其中任意一个都不能进行游戏,跳转回登录页面。

        :param request: aiohttp.web.Request
        :return: aiohttp.web.Response or aiohttp.web.HTTPFound
        """
        session = yield from get_session(request)
        token = session.get('api_token', None)
        starttime = session.get('api_starttime', None)
        world_ip = session.get('world_ip', None)
        if token and starttime and world_ip:
            context = {'scheme': request.scheme,
                       'host': request.host,
                       'token': token,
                       'starttime': starttime}
            return aiohttp_jinja2.render_template('flash.html', request, context)
        else:
            self.clear_session(session)
            return aiohttp.web.HTTPFound('/') 
Example #5
Source File: frontend.py    From ooi3 with GNU Affero General Public License v3.0 6 votes vote down vote up
def poi(self, request):
        """适配poi中进行游戏的页面,显示FLASH。该页面会检查会话中是否有api_token、api_starttime和world_ip三个参数,缺少其中任意一个
        都不能进行游戏,跳转回登录页面。

        :param request: aiohttp.web.Request
        :return: aiohttp.web.Response or aiohttp.web.HTTPFound
        """
        session = yield from get_session(request)
        token = session.get('api_token', None)
        starttime = session.get('api_starttime', None)
        world_ip = session.get('world_ip', None)
        if token and starttime and world_ip:
            context = {'scheme': request.scheme,
                       'host': request.host,
                       'token': token,
                       'starttime': starttime}
            return aiohttp_jinja2.render_template('poi.html', request, context)
        else:
            self.clear_session(session)
            return aiohttp.web.HTTPFound('/') 
Example #6
Source File: handlers.py    From aiohttp-login with ISC License 6 votes vote down vote up
def reset_password_allowed(request, confirmation):
    db = cfg.STORAGE
    form = await forms.get('ResetPassword').init(request)
    user = await db.get_user({'id': confirmation['user_id']})
    assert user

    while request.method == 'POST' and form.validate():
        await db.update_user(
            user, {'password': encrypt_password(form.password.data)})
        await db.delete_confirmation(confirmation)
        await authorize_user(request, user)
        flash.success(request, cfg.MSG_PASSWORD_CHANGED)
        flash.success(request, cfg.MSG_LOGGED_IN)
        return redirect(cfg.LOGIN_REDIRECT)

    return render_template(themed('reset_password_allowed.html'), request, {
        'auth': {
            'url_for': url_for,
            'cfg': cfg,
            'form': form,
        }
    }) 
Example #7
Source File: handlers.py    From aiohttp-login with ISC License 6 votes vote down vote up
def change_password(request):
    db = cfg.STORAGE
    user = request[cfg.REQUEST_USER_KEY]
    form = await forms.get('ChangePassword').init(request)

    while request.method == 'POST' and form.validate():
        if not check_password(form.cur_password.data, user['password']):
            form.cur_password.errors.append(cfg.MSG_WRONG_PASSWORD)
            break

        password = encrypt_password(form.new_password.data)
        await db.update_user(user, {'password': password})

        flash.success(request, cfg.MSG_PASSWORD_CHANGED)
        return redirect(request.path)

    return render_template(themed('change_password.html'), request, {
        'auth': {
            'cfg': cfg,
            'form': form,
            'url_for': url_for,
        }
    }) 
Example #8
Source File: service_a.py    From aiozipkin with Apache License 2.0 6 votes vote down vote up
def handler(request):
    await asyncio.sleep(0.01)
    session = request.app['session']

    resp = await session.get(service_b_api)
    data_b = await resp.json()

    resp = await session.get(service_e_api)
    data_e = await resp.json()

    tree = {
        'name': 'service_a',
        'host': host,
        'port': port,
        'children': [data_b, data_e],
    }
    ctx = {'zipkin': zipkin_ui_address, 'service': tree}
    return aiohttp_jinja2.render_template('index.html', request, ctx) 
Example #9
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_template_not_found():

    async def func(request):
        return aiohttp_jinja2.render_template('template', request, {})

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({}))

    app.router.add_route('GET', '/', func)

    req = make_mocked_request('GET', '/', app=app)

    with pytest.raises(web.HTTPInternalServerError) as ctx:
        await func(req)

    t = "Template 'template' not found"
    assert t == ctx.value.text
    assert t == ctx.value.reason 
Example #10
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_render_template(aiohttp_client):

    async def func(request):
        return aiohttp_jinja2.render_template(
            'tmpl.jinja2', request,
            {'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('*', '/', func)

    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 #11
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_render_not_initialized():

    async def func(request):
        return aiohttp_jinja2.render_template('template', request, {})

    app = web.Application()

    app.router.add_route('GET', '/', func)

    req = make_mocked_request('GET', '/', app=app)
    msg = "Template engine is not initialized, " \
          "call aiohttp_jinja2.setup(..., app_key={}" \
          ") first".format(aiohttp_jinja2.APP_KEY)

    with pytest.raises(web.HTTPInternalServerError) as ctx:
        await func(req)

    assert msg == ctx.value.text 
Example #12
Source File: test_jinja_globals.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_static_var_missing(aiohttp_client, caplog):

    async def index(request):
        with pytest.raises(RuntimeError, match='static_root_url'):
            aiohttp_jinja2.render_template('tmpl.jinja2', request, {})
        return web.Response()

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2':
         "{{ static('whatever.js') }}"}))

    app.router.add_route('GET', '/', index)
    client = await aiohttp_client(app)

    resp = await client.get('/')
    assert 200 == resp.status  # static_root_url is not set 
Example #13
Source File: test_jinja_globals.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_helpers_disabled(aiohttp_client):

    async def index(request):
        with pytest.raises(jinja2.UndefinedError,
                           match="'url' is undefined"):
            aiohttp_jinja2.render_template('tmpl.jinja2', request, {})
        return web.Response()

    app = web.Application()
    aiohttp_jinja2.setup(
        app,
        default_helpers=False,
        loader=jinja2.DictLoader(
            {'tmpl.jinja2': "{{ url('index')}}"})
    )

    app.router.add_route('GET', '/', index)
    client = await aiohttp_client(app)

    resp = await client.get('/')
    assert 200 == resp.status 
Example #14
Source File: middlewares.py    From dvpwa with MIT License 5 votes vote down vote up
def handle_40x(request, exc):
    response = render_template('errors/40x.jinja2',
                               request,
                               {'error': exc})
    return response 
Example #15
Source File: jinja_server.py    From us-pycon-2019-tutorial with Apache License 2.0 5 votes vote down vote up
def greet_user(request: web.Request) -> web.Response:

    context = {
        "username": request.match_info.get("username", ""),
        "current_date": "January 27, 2017",
    }
    template = "example.html"
    response = aiohttp_jinja2.render_template(template, request, context=context)
    return response 
Example #16
Source File: server.py    From us-pycon-2019-tutorial with Apache License 2.0 5 votes vote down vote up
def error_middleware(
    request: web.Request, handler: _WebHandler
) -> web.StreamResponse:
    try:
        return await handler(request)
    except web.HTTPException:
        raise
    except asyncio.CancelledError:
        raise
    except Exception as ex:
        return aiohttp_jinja2.render_template(
            "error-page.html", request, {"error_text": str(ex)}, status=400
        ) 
Example #17
Source File: 01-login-session.py    From us-pycon-2019-tutorial with Apache License 2.0 5 votes vote down vote up
def error_middleware(
    request: web.Request, handler: _WebHandler
) -> web.StreamResponse:
    try:
        return await handler(request)
    except web.HTTPException:
        raise
    except asyncio.CancelledError:
        raise
    except Exception as ex:
        return aiohttp_jinja2.render_template(
            "error-page.html", request, {"error_text": str(ex)}, status=400
        ) 
Example #18
Source File: 01-error-middleware.py    From us-pycon-2019-tutorial with Apache License 2.0 5 votes vote down vote up
def error_middleware(
    request: web.Request,
    handler: Callable[[web.Request], Awaitable[web.StreamResponse]],
) -> web.StreamResponse:
    try:
        return await handler(request)
    except web.HTTPException:
        raise
    except asyncio.CancelledError:
        raise
    except Exception as ex:
        return aiohttp_jinja2.render_template(
            "error-page.html", request, {"error_text": str(ex)}, status=400
        ) 
Example #19
Source File: rest_api.py    From caldera with Apache License 2.0 5 votes vote down vote up
def landing(self, request):
        access = await self.auth_svc.get_permissions(request)
        if not access:
            return render_template('login.html', request, dict())
        plugins = await self.data_svc.locate('plugins', {'access': tuple(access), **dict(enabled=True)})
        data = dict(plugins=[p.display for p in plugins], errors=self.app_svc.errors + self._request_errors(request), version=self.app_svc.version)
        return render_template('%s.html' % access[0].name, request, data) 
Example #20
Source File: handlers.py    From aiohttp-login with ISC License 5 votes vote down vote up
def template_handler(template, context=None):
    async def handler(request):
        return render_template(themed(template), request, context)
    return handler 
Example #21
Source File: handlers.py    From aiohttp-login with ISC License 5 votes vote down vote up
def confirmation(request):
    db = cfg.STORAGE
    code = request.match_info['code']

    confirmation = await db.get_confirmation({'code': code})
    if confirmation and is_confirmation_expired(confirmation):
        await db.delete_confirmation(confirmation)
        confirmation = None

    if confirmation:
        action = confirmation['action']

        if action == 'registration':
            user = await db.get_user({'id': confirmation['user_id']})
            await db.update_user(user, {'status': 'active'})
            await authorize_user(request, user)
            await db.delete_confirmation(confirmation)
            flash.success(request, cfg.MSG_ACTIVATED)
            flash.success(request, cfg.MSG_LOGGED_IN)
            return redirect(cfg.LOGIN_REDIRECT)

        if action == 'reset_password':
            return await reset_password_allowed(request, confirmation)

        if action == 'change_email':
            user = await db.get_user({'id': confirmation['user_id']})
            await db.update_user(user, {'email': confirmation['data']})
            await db.delete_confirmation(confirmation)
            flash.success(request, cfg.MSG_EMAIL_CHANGED)
            return redirect('auth_change_email')

    return render_template(themed('confirmation_error.html'), request, {
        'auth': {
            'cfg': cfg
        }
    }) 
Example #22
Source File: handlers.py    From aiohttp-login with ISC License 5 votes vote down vote up
def login(request):
    form = await forms.get('Login').init(request)

    while request.method == 'POST' and form.validate():

        user = await cfg.STORAGE.get_user({'email': form.email.data})
        if not user:
            form.email.errors.append(cfg.MSG_UNKNOWN_EMAIL)
            break

        if not check_password(form.password.data, user['password']):
            form.password.errors.append(cfg.MSG_WRONG_PASSWORD)
            break

        if user['status'] == 'banned':
            form.email.errors.append(cfg.MSG_USER_BANNED)
            break
        if user['status'] == 'confirmation':
            form.email.errors.append(cfg.MSG_ACTIVATION_REQUIRED)
            break
        assert user['status'] == 'active'

        await authorize_user(request, user)
        flash.success(request, cfg.MSG_LOGGED_IN)
        url = request.query.get(cfg.BACK_URL_QS_KEY, cfg.LOGIN_REDIRECT)
        return redirect(url)

    return render_template(themed('login.html'), request, {
        'auth': {
            'url_for': url_for,
            'cfg': cfg,
            'form': form,
            'social_url': social_url(request),
        }
    }) 
Example #23
Source File: middlewares.py    From dvpwa with MIT License 5 votes vote down vote up
def handle_50x(request, exc):
    response = render_template('errors/50x.jinja2',
                               request,
                               {'error': exc})
    return response 
Example #24
Source File: middlewares.py    From snare with GNU General Public License v3.0 5 votes vote down vote up
def handle_404(self, request):
        return aiohttp_jinja2.render_template(self.error_404, request, {}) 
Example #25
Source File: admin.py    From aiohttp_admin with Apache License 2.0 5 votes vote down vote up
def index_page(self, request):
        t = self._template
        context = {'name': self._name}
        return render_template(t, request, context, app_key=TEMPLATE_APP_KEY) 
Example #26
Source File: admin.py    From aiohttp_admin with Apache License 2.0 5 votes vote down vote up
def login_page(self, request):
        t = self._login_template
        context = {}
        return render_template(t, request, context, app_key=TEMPLATE_APP_KEY) 
Example #27
Source File: admin.py    From aiohttp_admin with Apache License 2.0 5 votes vote down vote up
def index_page(self, request):
        """
        Return index page with initial state for admin
        """
        context = {"initial_state": self.schema.to_json()}

        return render_template(
            self.template,
            request,
            context,
            app_key=TEMPLATE_APP_KEY,
        ) 
Example #28
Source File: web.py    From bioconda-utils with MIT License 5 votes vote down vote up
def handle_errors(request, handler):
    try:
        return await handler(request)
    except aiohttp.web.HTTPException as exc:
        if exc.status in (302,):
            raise
        try:
            return aiohttp_jinja2.render_template('bot_40x.html', request, {'exc':exc})
        except KeyError as XYZ:
            raise exc 
Example #29
Source File: jinja2.py    From aiohttp_apiset with Apache License 2.0 5 votes vote down vote up
def template(template_name, *, app_key=APP_KEY, encoding='utf-8', status=200):
    """
    Decorator compatible with aiohttp_apiset router
    """

    def wrapper(func):
        @functools.wraps(func)
        async def wrapped(*args, **kwargs):
            if asyncio.iscoroutinefunction(func):
                coro = func
            else:
                coro = asyncio.coroutine(func)
            context = await coro(*args, **kwargs)
            if isinstance(context, web.StreamResponse):
                return context

            if 'request' in kwargs:
                request = kwargs['request']
            elif not args:
                request = None
                warnings.warn("Request not detected")
            elif 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 #30
Source File: web.py    From avacity-2.0 with MIT License 5 votes vote down vote up
def index(request):
    session = await aiohttp_session.get_session(request)
    context = {}
    if "token" not in session:
        context["logged_in"] = False
    else:
        context["logged_in"] = True
        context["token"] = session["token"]
        context["update_time"] = config["webserver"]["update_time"]
    return aiohttp_jinja2.render_template("index.html", request,
                                          context=context)