目录
MultiDict:... 1
webob.Request对象:... 2
webob.Response对象:... 4
webob.dec装饰器:... 5
webob
environ,环境数据有很多,都存在dict中,字典存取没有像访问对象的属性使用方便;
使用第三方库webob,可把环境数据的解析、封装成对象;
https://docs.pylonsproject.org/projects/webob/en/stable/#
>pip install webob
常用:
webob.request
webob.response
webob.dec #decorator
webob.exc #exception
webob.multidict #特殊的字典,key可重复(允许一个key存多个值),因为网页中的表单框会有重名,如都叫name
特殊的字典,key可重复,允许一个key对应多个value;
往里添加时用add()方法,若用md['a']=2则会覆盖之前的value;
例:
from webob.multidict import MultiDict
md = MultiDict()
md.add(1, 'magedu')
md.add(1, '.com')
md.add('a', 1)
md.add('a', 2)
md['b'] = '3' #若此句放到md.add('b', 4)之后则是覆盖
md.add('b', 4)
for pair in md.items():
print(pair)
print(md.getall('a')) #获取'a'这个key对应的所有value
print(md.get('b')) #获取'b'这个key对应的一个value
print(md.get('c'))
print(md.getone('c')) #getone()只能有一个值,即'c'这个key只能对应一个value
输出:
(1, 'magedu')
(1, '.com')
('a', 1)
('a', 2)
('b', '3')
('b', 4)
[1, 2]
4
None
……
KeyError: "Multiple values match 'b': ['3', 4]"
将environ环境参数解析并封装成request对象;
GET方法,发送的数据是url中的query string,在request header中;
request.GET就是一个MultiDict字典,里面封装着查询字符串;
POST方法,提交的数据是放在request body里面,但也可同时使用query string;
request.POST可获取request body中的数据,也是个Multidict;
用chrome插件postman模拟POST请求;
用fiddler-->右侧composer模拟POST请求;
不关心什么方法提交,只关心数据,可用request.params,它里面是所有提交数据的封装;
注:
url中的query string,归request.GET管;
body中的表单,归request.POST管;
request.params,查询字符串和body中的提交表单都管;
例,webob.Request:
from webob import Request, Response
def application(environ, start_response):
request = Request(environ)
print(request.method)
print(request.path)
print(request.GET)
print(request.POST) #MultiDict()
print(request.params) #NetstedMultiDict()
print(request.query_string)
html = '<h2>test</h2>'.encode()
start_response("200 OK", [('Content-Type', 'text/html; charset=utf-8')])
return [html]
ip = '127.0.0.1'
port = 9999
server = make_server(ip, port, application)
server.serve_forever()
server.shutdown()
server.server_close()
输出:
GET
/index.html
GET([('id', '5'), ('name', 'jowin'), ('name', 'tom'), ('age', ''), ('age', '18,19')])
<NoVars: Not an HTML form submission (Content-Type: text/plain)>
NestedMultiDict([('id', '5'), ('name', 'jowin'), ('name', 'tom'), ('age', ''), ('age', '18,19')])
id=5&name=jowin&name=tom&age=&age=18,19
用fiddler模拟POST:
User-Agent: Fiddler
Content-Type: application/x-www-form-urlencoded
Host: 127.0.0.1:9999
输出:
POST
/index.php
GET([])
MultiDict([('index.html', ''), ('id', '5'), ('name', 'jowin'), ('name', 'chai'), ('age', ''), ('age', '18,19')])
NestedMultiDict([('index.html', ''), ('id', '5'), ('name', 'jowin'), ('name', 'chai'), ('age', ''), ('age', '18,19')])
查看源码:
class Response(object):
def __init__(self, body=None, status=None, headerlist=None, app_iter=None,
content_type=None, conditional_response=None, charset=_marker,
**kw):
def __call__(self, environ, start_response):
"""
WSGI application interface
"""
start_response(self.status, headerlist)
return self._app_iter #self._app_iter = app_iter,app_iter = [body]
例:
def application(environ, start_response):
request = Request(environ)
print(request.params)
res = Response()
print(res.status)
print(res.headerlist)
print(res.content_type)
print(res.charset)
print(res.status_code)
res.status_code = 200
html = '<h2>test</h2>'.encode()
res.body = html
start_response(res.status, res.headerlist)
return [html]
输出:
NestedMultiDict([('id', '5'), ('name', 'jowin'), ('name', 'tom'), ('age', ''), ('age', '18,19')])
200 OK
[('Content-Type', 'text/html; charset=UTF-8'), ('Content-Length', '0')]
text/html
UTF-8
200
例:
def application(environ, start_response):
request = Request(environ)
print(request.params)
res = Response()
print(res.status)
print(res.headerlist)
print(res.content_type)
print(res.charset)
print(res.status_code)
res.status_code = 200
html = '<h2>test</h2>'.encode()
res.body = html
return res(environ, start_response) #Response类中有__call__()方法,实例可调用
class wsgify(object):
RequestClass = Request
def __init__(self, func=None, RequestClass=None,
args=(), kwargs=None, middleware_wraps=None):
例:
from webob import Request, Response, dec
from wsgiref.simple_server import make_server
@dec.wsgify
def app(request:Request)->Response: #这种方式更贴合实际,进来request,出去response;app()函数应具有一个参数,是webob.Request类型,是对字典environ对象化后的实例,返回值必须是一个webob.Response类型,app()函数中应要创建一个webob.Response类型的实例
print(request.method)
print(request.path)
print(request.query_string)
return Response('<h2>test</h2>'.encode())
if __name__ == '__main__':
ip = '127.0.0.1'
port = 9999
server = make_server(ip, port, app)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.shutdown()
server.server_close()
输出:
GET
/index.html
id=5&name=jowin&name=tom&age=&age=18,19
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。