I use JinjaTemplate and return data to html this way
@router.get('/', response_class=HTMLResponse)
async def main_page(request: Request,
members: List = [e.value for e in MembersQuantity],
activity_service: ActivityService = Depends(),
):
activity = await activity_service.get()
return templates.TemplateResponse('base.html',
context={
'request': request,
'members': members,
'activities': activity,
}
)
There are dozens of such routs in the project. And each of them needs to have the same context variable. I need to pass variables in all the routers - for example user
.
I can write this way of passing the user
object (it store in Redis)
@router.get('/', response_class=HTMLResponse)
async def main_page(request: Request,
members: List = [e.value for e in MembersQuantity],
activity_service: ActivityService = Depends(),
):
activity = await activity_service.get()
user = None
if await is_authenticated(request):
user = await get_current_user(request)
return templates.TemplateResponse('base.html',
context={
'request': request,
'members': members,
'activities': activity,
'user': user,
}
)
template
<html>
<head>
<title>Item Details</title>
<link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
</head>
<body>
<a class="" href="{{ url_for('user_notification', pk=user.user_id) }}">
</body>
</html>
But doing it in every router is completely wrong.
I know of different ways to pass global variables using middleware
in request.state
or response.set_cookie
. But this methods are not suitable for security reasons.
How can I globally transfer the value I want to the context
for all the routs?