Now, with the basic understanding of getting started, we now need a simple and easy-to-use routing function comparable to flask or bottle, which can be used to map URLs to code with an adorner.
This, it's not hard. First, a module called Hi: hi.py:
1 ImportRe2 3 classHi:4 def __init__(self):5self.uri_map={}6self.uri_regex_map={}7 8 defRoute (Self,pattern,method):9 defWrapper_a (func):Tenself.uri_map[pattern]={'Method': Method,'Callback': func} Oneself.uri_regex_map[pattern]=re.compile (pattern) A defWrapper_b (req,res,param): - func (Req,res,param) - returnWrapper_b the returnwrapper_a - - defRun (self,req,res): - forKvinchSelf.uri_map.items (): + ifReq.method ()inchv['Method']: -m=Self.uri_regex_map[k].match (Req.uri ()) + ifm: Av['Callback'] (req,res,m.groupdict ()) at Break
Put it in the same directory as the index.py. The following is the new code after using the route adorner:
1 ImportSYS2Sys.path.append ('/usr/local/nginx/python')3 4 fromHiImportHi5App =hi ()6 7 8@app. Route (R"^/$",['GET'])9 defHello_world (req,res,param):TenRes.header ('Content-type','Text/plain;charset=utf-8') OneRes.content ('Hello,world') ARes.status (200) - -@app. Route (R"^/client/?$",['GET','POST']) the defClient (Req,res,param): -Res.content ('{}<br>{}<br>{}<br>{}<br>{}'. Format (Req.client (), Req.method (), Req.uri (), Req.user_agent (), Req.param ())) -Res.status (200) - +@app. Route (R"^/hello/(? p<who>\w+)? $",['GET']) - defHello (req,res,param): +Res.content ('{}={}'. Format ('W.H.O.', param['W.H.O.'])) ARes.status (200) at - - - if __name__=='__main__': -App.run (Hi_req,hi_res)
Is it as simple as some flask or bottle? And it's much faster.
Visit Http://localhost:8080/,http://localhost:8080/client?a=90,http://localhost:8080/hello/cnblogs to see the results.
Web development based on Hi-nginx (python)--Route Adorner