Skip to content

Commit 52c4e5e

Browse files
committed
Add doc chapter about processing custom conditions for routes lookup
1 parent 1deea66 commit 52c4e5e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

docs/web.rst

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,48 @@ so application developer can use classes if he wants::
127127
app.router.add_route('GET', '/intro', handler.handle_intro)
128128
app.router.add_route('GET', '/greet/{name}', handler.handle_greeting)
129129

130+
Custom conditions for routes lookup
131+
-----------------------------------
132+
133+
Sometimes you need to distinguish *web-handlers* on more complex
134+
criteria than *HTTP method* and *path*.
135+
136+
While :class:`UrlDispatcher` doesn't accept extra criterias there is
137+
easy way to do the task by implementing the second routing layer by
138+
hands.
139+
140+
The example shows custom processing based on *HTTP Accept* header::
141+
142+
class Handler:
143+
144+
def __init__(self):
145+
self._accepts = {}
146+
147+
@asyncio.coroutine
148+
def do_route(self, request):
149+
acceptor = self._accepts.get(request.headers.get('ACCEPT'))
150+
if acceptor is None:
151+
raise HTTPNotAcceptable()
152+
return yield from acceptor(request)
153+
154+
def reg_acceptor(self, accept, handler):
155+
self._accepts[accept] = handler
156+
157+
158+
@asyncio.coroutine
159+
def handle_json(request):
160+
# do json handling
161+
162+
@asyncio.coroutine
163+
def handle_xml(request):
164+
# do xml handling
165+
166+
handler = Handler()
167+
app.router.add_route('GET', '/', handler.do_route)
168+
handler.reg_acceptor('application/json', handle_json)
169+
handler.reg_acceptor('application/xml', handle_xml)
170+
171+
130172

131173
.. _aiohttp-web-file-upload:
132174

0 commit comments

Comments
 (0)