当前位置: 移动技术网 > IT编程>脚本编程>Python > 基于hi-nginx的web开发(python篇)——动态路由和请求方法

基于hi-nginx的web开发(python篇)——动态路由和请求方法

2018年03月25日  | 移动技术网IT编程  | 我要评论

育儿知识网,邮购网站,韦德过人集锦

hi.py 的提供的路由装饰器接受两个参数,第一个参数指定动态路由的正则模式,第二个参数指定同意的http请求方法列表。

比如:

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)

这个路由指定uri为/client或者/client/,同时请求方法为GET或者POST的http请求由函数client(req,res,param)来处理。uri模式由正则表达式构成,请求方法参数由一个list表示,可接受的方法名包括:GET,POST,PUT,HEAD,PATCH等,凡nginx能理解的http方法名均可。

处理函数有三个参数,分别是req,res和param。它们分别是hi_req,hi_res和由正则表达式引出的group dict。前两者是有hi-nginx提供的api,它们提供一系列方法来操控http协议:

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

处理函数的第三个参数param可用来解析由正则模式提供的数据,比如:

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)

正则模式 ^/hello/(?P<who>\w+)?$ 是python re模块可以理解的模式,当uri为/hello/cnblogs时,其中的参数param就会是一个包含以who为键,以cnblogs为其值的dict字典。因此,它可以用来为操作函数提供表单以外的数据,还能美化uri。比如/hello?who=cnblogs就不如/hello/cnblogs美观简洁。

另外,同一个操作函数也可以对应多个路由规则,比如:

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)

在上面的代码中,操作函数hello_world在uri为/或者/test或者/test/时均能被调用,前提是一个要求请求方法是GET,另一个则要求是POST方法。这种一个函数对应多个路由的功能消除了写下面这种代码的麻烦:

1 if req.method()=='GET':
2     ...
3 if req.method()=='POST':
4     ...

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网