WSGI.解析GET请求

9 篇文章 0 订阅
3 篇文章 0 订阅

再次运行environment.py,这次这样调用它:

http://localhost:8051/?age=10&hobbies=software&hobbies=tunning

注意环境字典中的

QUERY_STRING和REQUEST_METHOD变量。当请求方法是GET的时候,表单变量将通过URL中叫做查询字符串的部分传递,那就是任何在?之后的东西。我们这里的查询字符串是age=10&hobbies=software&hobbies=tunning,注意hobbies在这里出现两次。这在表单中有复选框或用户在URL中输入多于一次相同的变量的情况下会发生。


可以写代码来解析查询字符串并取到那些值,但是使用CGI的模块parse_qs函数更简单,这个函数将返回一个字典,值都是列表。


要一直小心应对用户的输入。清理它来避免脚本注入。CGI的escape函数可以用来做这件事情。


#!/usr/bin/env python


from wsgiref.simple_server import make_server
from cgi import parse_qs, escape


html = """
<html>
<body>
   <form method="get" action="parsing_get.wsgi">
      <p>
         Age: <input type="text" name="age">
         </p>
      <p>
         Hobbies:
         <input name="hobbies" type="checkbox" value="software"> Software
         <input name="hobbies" type="checkbox" value="tunning"> Auto Tunning
         </p>
      <p>
         <input type="submit" value="Submit">
         </p>
      </form>
   <p>
      Age: %s<br>
      Hobbies: %s
      </p>
   </body>
</html>"""


def application(environ, start_response):


   # Returns a dictionary containing lists as values.
   d = parse_qs(environ['QUERY_STRING'])


   # In this idiom you must issue a list containing a default value.
   age = d.get('age', [''])[0] # Returns the first age value.
   hobbies = d.get('hobbies', []) # Returns a list of hobbies.


   # Always escape user input to avoid script injection
   age = escape(age)
   hobbies = [escape(hobby) for hobby in hobbies]


   response_body = html % (age or 'Empty',
               ', '.join(hobbies or ['No Hobbies']))


   status = '200 OK'


   # Now content type is text/html
   response_headers = [('Content-Type', 'text/html'),
                  ('Content-Length', str(len(response_body)))]
   start_response(status, response_headers)


   return [response_body]


httpd = make_server('localhost', 8051, application)
# Now it is serve_forever() in instead of handle_request().
# In Windows you can kill it in the Task Manager (python.exe).
# In Linux a Ctrl-C will do it.
httpd.serve_forever()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值