WSGI.解析GET请求
来源:互联网 发布:飞利浦剃须刀推荐 知乎 编辑:程序博客网 时间:2024/06/06 23:55
再次运行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()
- WSGI.解析GET请求
- WSGI: 解析GET请求
- WSGI.解析POST请求
- WSGI: 解析POST请求
- web python -- WSGI接口GET请求
- WSGI解析
- mknetworkkit get请求 + json 解析
- requests get请求+json解析
- requests get 请求解析xml
- http get/post请求及json解析
- IOS接口解析(GET请求)
- Netty4 HTTP请求参数解析(GET, POST)
- Get网络请求解析json串
- HTTP的post和get请求解析
- Get 请求中文参数乱码解析
- Netty4 HTTP请求参数解析(GET, POST)
- web python -- WSGI接口POST请求
- python wsgi 详解浏览器请求过程
- 表单放置自定义上传组件(C#)
- 解决git乱码的问题
- poj 2502 (为过)
- android---MediaRecorder
- Java 验证码
- WSGI.解析GET请求
- Android 短信 彩信 wap push的接收
- 拖拽面板
- smarty的简明安装配置
- 用hive+hdfs+sqoop分析日志的步骤
- hdu4013树的最小表示
- linux服务器下mysql设置主从同步的过程
- 类级框架
- C++ 编码转换