Request and Response

Pylon magic 全局变量

Pylons 有 几个 magic 全局变量,其中包含当前请求的状态数据。以下是最接近 Pyramid 的等价物:

pylons.request

The request URL, query parameters, etc. In Pyramid it's the request argument to view functions and self.request in view methods (if your class constructor follows the normal pattern). In templates it's requestreq (starting in Pyramid 1.3). In pshell or unit tests where you can't get it any other way, use request = pyramid.threadlocal.get_current_request() .

pylons.response

HTTP响应状态和文档。Pyramid没有全局响应对象。相反,您的视图应该创建一个 pyramid.response.Response 实例并返回。如果使用渲染器,它将为您创建一个响应对象。

request.response object available which you can set attributes on and return, but it will have effect only if you return it. If you're using a renderer, it will honor changes you make to request.response .

pylons.session

Session variables. See the Sessions chapter.

pylons.tmpl_context

用于请求本地数据的临时对象,通常用于将变量传递给模板。在Pyramid中,返回变量的dict并让渲染器将其应用到模板。Or you can render a template yourself in view code.

view every

Pyramid does have a port of "tmpl_context" at request.tmpl_context , which is visible in templates as c . However, it never caught on among Pyramid-Pylons users and is no longer documented.

pylons.app_globals

Global variables shared across all requests. The nearest equivalent is request.registry.settings . This normally contains the application settings, but you can also store other things in it too. (The registery is a singleton used internally by Pyramid.)

pylons.cache

缓存对象,用于跨多个请求在一段时间内自动保存昂贵计算的结果。Pyramid没有内置的等价物,但您可以使用“Pyramid烧杯”设置缓存。您可能想将缓存放在设置中?

pylons.url

URL生成器。Pyramid的请求对象具有生成URL的方法。另请参阅url生成器一章,了解减少样板代码的便利对象。

Request and response API

Pylons 使用WebOB的请求和响应对象。 Pyramid 使用这些子类,因此所有熟悉的属性和方法都有: paramsGETPOSTheadersmethodcharsetdateenvironbodybody_file . The most commonly-used attribute is params , which is the query parameters and POST variables.

Pyramid adds several attributes and methods. contextmatchdictmatched_routeregistryregistry.settingssessiontmpl_context access the request's state data and global application data. route_pathroute_urlresource_urlstatic_url 生成URL。

我们不再重复这些属性和方法的现有文档,而是将您引向原始文档:

Response examples:

 1response = request.response
 2
 3# -OR-
 4from pyramid.response import Response
 5response = Response
 6
 7# In either case.
 8response.status = "200 OK"
 9response.status_int = 200
10response.content_type = "text/plain"
11response.charset = "utf-8"
12response_headerlist = [
13    ("Set-Cookie", "abc=123"), ("X-My-Header", "foo")]
14response_cache_for = 3600    # Seconds
15return response