Web development based on hi-nginx (python)-Dynamic Routing and request method, hi-nginxpython
The route decorator provided by hi. py accepts two parameters: the first parameter specifies the regular mode of the dynamic route, and the second parameter specifies the list of http request methods agreed.
For example:
1 @app.route(r"^/client/?$",['GET','POST'])2 def client(req,res,param):3 res.content('{}<br>{}<br>{}<br>{}<br>{}'.format(req.client(),req.method(),req.uri(),req.user_agent(),req.param()))4 res.status(200)
This route specifies the uri as/client or/client/, and the http Request Method of GET or POST is processed by the function client (req, res, param. The uri mode is composed of regular expressions. The request method parameters are represented by a list. acceptable method names include GET, POST, PUT, HEAD, and PATCH, all http method names that nginx can understand can be used.
The processing function has three parameters: req, res, And param. They are hi_req, hi_res, and group dict derived from regular expressions. The first two are APIs provided by hi-nginx, which provide a series of methods to manipulate the http protocol:
Hi_req
- Uri
- Method
- Client
- Param
- User_agent
- Has_header
- Get_header
- Has_form
- Get_form
- Has_session
- Get_session
- Has_cookie
- Get_cookie
Hi_res
- Status
- Content
- Header
- Session
The third parameter param of the processing function can be used to parse the data provided by the regular expression mode. For example:
1 @app.route(r"^/hello/(?P<who>\w+)?$",['GET'])2 def hello(req,res,param):3 res.content('{}={}'.format('who',param['who']))4 res.status(200)
Regular Expression ^/hello /(? P <who> \ w + )? $ Is a mode that can be understood by the python re module. When the uri is/hello/cnblogs, The param parameter will be a key containing the who, dict dictionary with cnblogs as its value. Therefore, it can be used to provide data other than the form for the operation function and beautify the uri. For example,/hello? Who = cnblogs is not as elegant and concise as/hello/cnblogs.
In addition, the same operation function can also correspond to multiple routing rules, such:
1 @app.route(r'^/test/?$',['POST'])2 @app.route(r"^/$",['GET'])3 def hello_world(req,res,param):4 res.header('Content-Type','text/plain;charset=utf-8')5 res.content('hello,world')6 res.status(200)
In the above Code, the operation function hello_world can be called when the uri is // or/test/, provided that the request method is GET and the request method is POST. This function corresponds to multiple routes to eliminate the trouble of writing the following code:
1 if req.method()=='GET':2 ...3 if req.method()=='POST':4 ...