官方API:pyramid.request、pyramid.response 和 pyramid.httpexceptions。
Pyramid中的request对象和response对象是基于WebOb包的(WebOb包是一个python库,对 WSGI 的request和response进行了封装)。
所以,传递给视图的request对象是
pyramid.request.Request的一个实例,而pyramid.request.Request是 webob.Request的子类。返回的response对象是pyramid.request.Response的一个实例,而pyramid.request.Response是 webob.Response的子类。
#1.Request request对象有很多属性(当然也可以包含你自定义的属性)。下面介绍一些比较重要的:
- **request.method:**request请求方式,比如POST,GET。
- **request.GET:**一个包含所有get请求数据的 multidict 字典,就是URL中的查询字符串。
- **request.POST:**一个包含request body的所有数据的 multidict 字典,必须是POST形式提交的表单。
- **request.params:**这货是request.GET和request.POST的结合。也是一个 multidict 字典。
- **request.body:**包含整个request的内容,当你不是以一个表单的形式发送POST请求时,或者发送一个PUT请求时,它会很有用的。
- request.json_body:看名字都知道,是json形式的request body。 JSON形式的request body。用来返回json形式的request body数据,如果request没有body或者body不是json形式的,就会抛出一个异常。
- request.cookies: 一个包含所有cookies的字典。
- request.headers: 一个包含所有headers的字典。
下面介绍request中与URL有关的一些属性,以http://localhost/app/blog?id=10为例(假设应用安装在http://localhost/app)
- **request.url:**获得整个url,如
http://localhost/app/blog?id=10。 - **request.host:**获得host信息,如localhost。
- **request.host_url:**host和url,如
http://localhost。 - **request.application_url:**应用的url,如
http://localhost/app。 - **reqeust.path_url:**完整路径,如
http://localhost/app/blog - **request.path:**去掉host信息的路径,如/app/blog。
- req.path_qs:在request.path基础上加了查询字符串,如/app/blog?id=10。
- **req.query_string:**查询字符串,如 id=10。
request还有一个属性charset,用来设定字符编码。比如你可以在实例化request对象时设定Request(environ,charset='utf-8').也可以指定req.charset='utf-8'。如果你这样设定了,那么req.POST, req.GET, req.params, 还有req.cookies都会包含unicode字符串。每一个方法都有一个对应的获取str的方法,比如 req.str_POST,request.str_GET等等。
#2.Multidict multidict是一个特殊的字典,一个key可以对应多个值。
比如有这样一个查询字符串 ?pref=red&pref=blue;pref有red和blue两个值。当你用request.GET['pref']时会返回blue,它只返回最后的那个值。如果你想返回所有的值,用request.getall('pref')。Multidict就是元组的列表的一个视图,所有的键和值都会被排序好。
#3.Response 一个response对象包含3个基本的部分:
-
**response.status:**返回信息,比如'200 OK',如果你不想返回信息,而是想返回一个一个值,可以用status_int,比如response.status_int=200。
-
**response.headerlist:**包含所有header信息的列表,就像 [('Content-Type', 'text/html')]这样。(你也可以用response.headers访问header)。
-
**response.app_iter:**产生response内容的可迭代对象(比如list和generator生成器)。也可以用其他属性访问,只不过形式不一样,比如response.body(字符串),response.unicode_body(一个unicode对象), response.body_file(一个file-like对象)
其他属性还有:
-
**response.content_type:**设置content type(不包括charset参数),比如:response.content_type ='text/html'。
-
**response.set_cookie(key, value, max_age=None, path='/', ...):**设置cookie。
-
**response.delete_cookie(key, path='/', domain=None):**删除cookie。
-
**response.cache_expires(seconds=0):**设置缓存失效时间。
-
response(environ, start_response): WSGI应用程序。
最后还有一个pyramid.httpexceptions模块,告诉Pyramid当你response产生异常时该返回什么。
