Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow context_processors to compose from parent apps. #195

Merged
merged 3 commits into from
Apr 11, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion aiohttp_jinja2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,8 @@ async def wrapped(*args):
@web.middleware
async def context_processors_middleware(request, handler):

request[REQUEST_CONTEXT_KEY] = {}
if REQUEST_CONTEXT_KEY not in request:
request[REQUEST_CONTEXT_KEY] = {}
for processor in request.app[APP_CONTEXT_PROCESSORS_KEY]:
request[REQUEST_CONTEXT_KEY].update(await processor(request))
return await handler(request)
Expand Down
46 changes: 46 additions & 0 deletions tests/test_context_processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,52 @@ async def processor(request):
assert 'foo: 1, bar: 2, path: /' == txt


async def test_nested_context_processors(aiohttp_client):

@aiohttp_jinja2.template('tmpl.jinja2')
async def func(request):
return {'bar': 2}

subapp = web.Application(middlewares=[
aiohttp_jinja2.context_processors_middleware])
aiohttp_jinja2.setup(subapp, loader=jinja2.DictLoader(
{'tmpl.jinja2':
'foo: {{ foo }}, bar: {{ bar }}, baz: {{ baz }}, path: {{ request.path }}'}))

async def subprocessor(request):
return {'foo': 1,
'bar': 'should be overwriten'}

subapp['aiohttp_jinja2_context_processors'] = (
aiohttp_jinja2.request_processor,
subprocessor,
)

subapp.router.add_get('/', func)

app = web.Application(middlewares=[
aiohttp_jinja2.context_processors_middleware])
aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({}))

async def processor(request):
return {'baz': 5}

app['aiohttp_jinja2_context_processors'] = (
aiohttp_jinja2.request_processor,
processor,
)

app.add_subapp('/sub/', subapp)


client = await aiohttp_client(app)

resp = await client.get('/sub/')
assert 200 == resp.status
txt = await resp.text()
assert 'foo: 1, bar: 2, baz: 5, path: /sub/' == txt


async def test_context_is_response(aiohttp_client):

@aiohttp_jinja2.template('tmpl.jinja2')
Expand Down