router.rst (2706B)
1 Router 2 ====== 3 4 The router is used to match incoming requests to request handler 5 functions. Typically users don't interact with the router directly, 6 but instead send a list of routes to register when starting the 7 server. However it is also possible to add routes after starting the 8 server by calling the `register` method on the server's `router` 9 property. 10 11 Routes are represented by a three item tuple:: 12 13 (methods, path_match, handler) 14 15 `methods` is either a string or a list of strings indicating the HTTP 16 methods to match. In cases where all methods should match there is a 17 special sentinel value `any_method` provided as a property of the 18 `router` module that can be used. 19 20 `path_match` is an expression that will be evaluated against the 21 request path to decide if the handler should match. These expressions 22 follow a custom syntax intended to make matching URLs straightforward 23 and, in particular, to be easier to use than raw regexp for URL 24 matching. There are three possible components of a match expression: 25 26 * Literals. These match any character. The special characters \*, \{ 27 and \} must be escaped by prefixing them with a \\. 28 29 * Match groups. These match any character other than / and save the 30 result as a named group. They are delimited by curly braces; for 31 example:: 32 33 {abc} 34 35 would create a match group with the name `abc`. 36 37 * Stars. These are denoted with a `*` and match any character 38 including /. There can be at most one star 39 per pattern and it must follow any match groups. 40 41 Path expressions always match the entire request path and a leading / 42 in the expression is implied even if it is not explicitly 43 provided. This means that `/foo` and `foo` are equivalent. 44 45 For example, the following pattern matches all requests for resources with the 46 extension `.py`:: 47 48 *.py 49 50 The following expression matches anything directly under `/resources` 51 with a `.html` extension, and places the "filename" in the `name` 52 group:: 53 54 /resources/{name}.html 55 56 The groups, including anything that matches a `*` are available in the 57 request object through the `route_match` property. This is a 58 dictionary mapping the group names, and any match for `*` to the 59 matching part of the route. For example, given a route:: 60 61 /api/{sub_api}/* 62 63 and the request path `/api/test/html/test.html`, `route_match` would 64 be:: 65 66 {"sub_api": "html", "*": "html/test.html"} 67 68 `handler` is a function taking a request and a response object that is 69 responsible for constructing the response to the HTTP request. See 70 :doc:`handlers` for more details on handler functions. 71 72 .. _router.Interface: 73 74 :mod:`Interface <wptserve.router>` 75 ---------------------------------- 76 77 .. automodule:: wptserve.router 78 :members: