One, routing
1.1 What is routing
Simply put, that is the way to go. is to distribute the data according to different paths.
URLs are paths to different resources, and different paths should be handled by different applications.
Therefore, you need to increase the branch processing of the path in the code.
A simple routing requirement:
| Path |
Content |
| / |
Back to welcome information |
| /python |
Back to Hello Python |
| Other paths |
Returns 404 |
1.2 When to handle routing
The processing of the route requires that the WSGI server WSGI the server environment variable after it receives the HTTP request, and then the Request.path should be processed to invoke the appropriate application according to path.
1.3 How to handle routing
The simplest route processing is conditional judgment, but it needs to be judged rigorously.
Second, the route processing
2.1 Article Judgment
From wsgiref.simple_server import make_serverfrom webob import request, Response, dec@dec.wsgifydef app (request), Re Sponse:print (request.method) print (request.path) print (request.query_string) print (Request. GET) print (Request. POST) Print (request.params) res = Response () if Request.path = = '/': Res.status_code = Res.cont Ent_type = ' text/html ' res.charset = ' utf-8 ' res.body = '
2.2 Functional condition Matching
From wsgiref.simple_server import make_serverfrom webob import Request, Response, decdef Index (request:request): retur N Response ('
2.3 Increasing the dynamic registration of a route
From wsgiref.simple_server import make_serverfrom webob import Request, Response, decdef Index (request:request): Return Response ('
2.4 Routing encapsulation into class
From wsgiref.simple_server import make_serverfrom webob import Request, Response, Dec, Excclass application:def Notfou nd (self, request:request): res = Response () Res.status_code = 404 Res.body = '
2.5 Simplifying the Routing class
From wsgiref.simple_server import make_serverfrom webob import Request, Response, Dec, Excclass application:routetable = {} @classmethod def register (CLS, path): Def _register (handler): CLS. Routetable[path] = handler return handler return _register @dec. Wsgify def __call__ (self, request) -Response:try:return self. Routetable[request.path] (Request) Except:raise exc. Httpnotfound (' The page you visited was hijacked by aliens ') @Application. Register ('/') def index (request:request): Return Response ('
Iii. SummaryThe routing feature should be designed in the simplest way, and then step-by-step, such as: Avoid routing logic to write dead in code, code optimization.
[Python Web Development] Routing implementation (III)