Web development based on Hi-nginx (python)--Route Adorner

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.