@@ -446,10 +446,13 @@ Request's storage
446446^^^^^^^^^^^^^^^^^
447447
448448Variables that are only needed for the lifetime of a :class: `Request `, can be
449- stored in a :class: `Request `::
449+ stored in a :class: `Request `. Similarly to :class: `Application `, :class: `RequestKey `
450+ instances or strings can be used as keys::
451+
452+ my_private_key = web.RequestKey("my_private_key", str)
450453
451454 async def handler(request):
452- request[' my_private_key' ] = "data"
455+ request[my_private_key] = "data"
453456 ...
454457
455458This is mostly useful for :ref: `aiohttp-web-middlewares ` and
@@ -464,9 +467,11 @@ also support :class:`collections.abc.MutableMapping` interface. This is useful
464467when you want to share data with signals and middlewares once all the work in
465468the handler is done::
466469
470+ my_metric_key = web.ResponseKey("my_metric_key", int)
471+
467472 async def handler(request):
468473 [ do all the work ]
469- response['my_metric' ] = 123
474+ response[my_metric_key ] = 123
470475 return response
471476
472477
@@ -722,18 +727,20 @@ In contrast, when accessing the stream directly (not recommended in middleware):
722727
723728When working with raw stream data that needs to be shared between middleware and handlers::
724729
730+ raw_body_key = web.RequestKey("raw_body_key", bytes)
731+
725732 async def stream_parsing_middleware(
726733 request: web.Request,
727734 handler: Callable[[web.Request], Awaitable[web.StreamResponse]]
728735 ) -> web.StreamResponse:
729736 # Read stream once and store the data
730737 raw_data = await request.content.read()
731- request['raw_body' ] = raw_data
738+ request[raw_body_key ] = raw_data
732739 return await handler(request)
733740
734741 async def handler(request: web.Request) -> web.Response:
735742 # Access the stored data instead of reading the stream again
736- raw_data = request.get('raw_body' , b'')
743+ raw_data = request.get(raw_body_key , b'')
737744 return web.Response(body=raw_data)
738745
739746Example
0 commit comments