Differences between revisions 1 and 2
Revision 1 as of 2006-03-30 07:44:43
Size: 13183
Editor: WeiZhong
Comment:
Revision 2 as of 2006-03-30 07:48:31
Size: 12986
Editor: WeiZhong
Comment:
Deletions are marked like this. Additions are marked like this.
Line 3: Line 3:
= Request and response objects = = Request response 对象 =
Line 15: Line 15:
``path`` path
Line 17: Line 17:
    Example: ``"/music/bands/the_beatles/"``

``GET``
    Example: "/music/bands/the_beatles/"

GET
Line 22: Line 22:
``POST`` POST
Line 25: Line 25:
``REQUEST`` REQUEST
Line 32: Line 32:
``COOKIES`` COOKIES
Line 35: Line 35:
``FILES`` FILES
Line 43: Line 43:
``META`` META
Line 47: Line 47:
    === CONTENT_LENGTH``
    === CONTENT_TYPE``
    === HTTP_ACCEPT_ENCODING``
    === HTTP_ACCEPT_LANGUAGE``
    === CONTENT_LENGTH
    === CONTENT_TYPE
    === HTTP_ACCEPT_ENCODING
    === HTTP_ACCEPT_LANGUAGE
Line 56: Line 56:
    === REQUEST_METHOD === A string such as ``"GET"`` or ``"POST"``.请求方式,比如 GET 或 POST     === REQUEST_METHOD === A string such as "GET" or "POST".请求方式,比如 GET 或 POST
Line 60: Line 60:
``user``
    一个 django.models.auth.users.User`` 对象表示当前登录用户.如果当前没有用户登录, user 被设置成 django.contrib.auth.models.AnonymousUser 的一个实例.你可以用 is_anonymous() 来区分登录用户和未登录用户.就象下面这样:
user
    一个 django.models.auth.users.User 对象表示当前登录用户.如果当前没有用户登录, user 被设置成 django.contrib.auth.models.AnonymousUser 的一个实例.你可以用 is_anonymous() 来区分登录用户和未登录用户.就象下面这样:
Line 68: Line 68:
``session``
        一个可读写的,类似字典的对象,表示当前的 session. 当有你的django 安装包括session支持并且被激活,该对象才存在.要了解关于session的更多细节,阅读session文档.
    .. _`session documentation`
: http://www.djangoproject.com/documentation/sessions/

``raw_post_data``
session
        一个可读写的,类似字典的对象,表示当前的 session. 当有你的django 安装包括session支持并且被激活,该对象才存在.要了解关于session的更多细节,阅读session文档: http://www.djangoproject.com/documentation/sessions/

raw_post_data
Line 75: Line 74:
`__`getitem`__`(key)`` `__`getitem`__`(key)
Line 80: Line 79:
``has_key()`` has_key()
Line 83: Line 82:
``get_full_path()`` get_full_path()
Line 85: Line 84:
    Example: ``"/music/bands/the_beatles/?print=true"``     Example: "/music/bands/the_beatles/?print=true"
Line 93: Line 92:
=== __getitem`__`(key) ===
        返加给定键的值. 如果该键有多个值, __getitem__ 返回最后一个值
=== __getitem__(key) ===
        返加给定键的值. 如果该键有多个值, `__getitem__` 返回最后一个值
Line 135: Line 134:
=== setlist(key, list_) === 不同于 __setitem`__`() ,将给定的键的值设置为一个列表 === setlist(key, list_) === 不同于 `__`setitem`__`() ,将给定的键的值设置为一个列表
Line 144: Line 143:
      Example: ``"a=2&b=3&b=5"``.       Example: "a=2&b=3&b=5".
Line 199: Line 198:
`__`init`__`(content='', mimetype=DEFAULT_MIME_TYPE)`` `__`init`__`(content='', mimetype=DEFAULT_MIME_TYPE)
Line 202: Line 201:
`__`setitem`__`(header, value)`` `__`setitem`__`(header, value)
Line 205: Line 204:
`__`delitem`__`(header)`` `__`delitem`__`(header)
Line 208: Line 207:
`__`getitem`__`(header)`` `__`getitem`__`(header)
Line 211: Line 210:
``has_header(header)`` has_header(header)
Line 214: Line 213:
``set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None)`` set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None)
Line 217: Line 216:
        * expires 是一个这种格式的字符串: ``"Wdy, DD-Mon-YY HH:MM:SS GMT"``.         * expires 是一个这种格式的字符串: "Wdy, DD-Mon-YY HH:MM:SS GMT".
Line 221: Line 220:
``delete_cookie(key)`` delete_cookie(key)
Line 224: Line 223:
``get_content_as_string(encoding)`` get_content_as_string(encoding)
Line 227: Line 226:
``write(content)``, ``flush()`` and ``tell()`` write(content), flush() and tell()
Line 231: Line 230:
``HttpResponseRedirect`` HttpResponseRedirect
Line 234: Line 233:
``HttpResponsePermanentRedirect`` HttpResponsePermanentRedirect
Line 237: Line 236:
``HttpResponseNotModified`` HttpResponseNotModified
Line 240: Line 239:
``HttpResponseNotFound``
    Acts just like ``HttpResponse`` but uses a 404 status code.

``HttpResponseForbidden``
    Acts just like ``HttpResponse`` but uses a 403 status code.

``HttpResponseGone``
    Acts just like ``HttpResponse`` but uses a 410 status code.

``HttpResponseServerError``
    Acts just like ``HttpResponse`` but uses a 500 status code.
HttpResponseNotFound
    Acts just like HttpResponse but uses a 404 status code.

HttpResponseForbidden
    Acts just like HttpResponse but uses a 403 status code.

HttpResponseGone
    Acts just like HttpResponse but uses a 410 status code.

HttpResponseServerError
    Acts just like HttpResponse but uses a 500 status code.

*本文档基于 Django magic-removal 分支,翻译时间是 2006-03-30 TableOfContents

Request 和 response 对象

概述

Django 使用 request 和 response 对象表示系统状态数据.

当请求一个页面时,Django创建一个 HttpRequest 对象.该对象包含 request 的元数据. 然后 Django 调用相应的 view 函数(HttpRequest 对象自动传递给该view函数<作为第一个参数>), 每一个 view 负责返回一个 HttpResponse 对象.

本文档解释了 HttpRequestHttpResponse 对象的 API

HttpRequest 对象

属性

除了 session 以外的其它属性都应该被看作是只读的

path

  • 一个字符串表示请求页的路径全名(不包括域名) Example: "/music/bands/the_beatles/"

GET

  • 可以认为是一个字典对象,包括所有的 HTTP GET 参数,参见下面的 QueryDict 文档

POST

  • 可以认为是一个字典对象,包括所有的 HTTP POST 参数,参见下面的 QueryDict 文档

REQUEST

  • 为了使用方便,该对象也可以认为是一个字典对象,它包括所有 POST 和 GET 数据(先POST,后GET). (类似PHP的 $_REQUEST 全局变量) 举例: 如果 GET={"name":"john"}, POST={"AGE":"34"} 则 REQUEST["name"]="john", REQUEST["age"]="34" 强烈建议你使用 GET 或 POST 而不是 REQUEST,因为前者更清晰.

COOKIES

  • 是一个标准的Python字典,包括所有的cookie. 键和值都是字符串.

FILES

  • 可以看作是一个字典对象,它包含所有的上载文件. FILES中的每个键是 <input type="file" name="" /> 中name 的值,每个值是一个标准的Python字典,该字典有以下三个键:

  • filename -- 上传文件的文件名,一个python 字符串
  • content-type 上传文件的 content type
  • content 上传文件的原始内容 注意 FILES 只有在请求方式为 POST 并且表单包括 enctype="multipart/form-data" 属性时才会有数据,否则 FILES 就是一个空的类似字典的对象.

META

  • META是一个标准的Python字典,包含所有可能的 HTTP 头. 可用的 header 依赖客户机和服务器,下面是某些可能的值:
  • === CONTENT_LENGTH === CONTENT_TYPE === HTTP_ACCEPT_ENCODING === HTTP_ACCEPT_LANGUAGE === HTTP_REFERER === The referring page, if any. 引用页,如果有的话 === HTTP_USER_AGENT === The client's user-agent string. 客户机用户代理字符串 === QUERY_STRING === The query string, as a single (unparsed) string.查询字符串,单一的未解析的字符串 === REMOTE_ADDR === The IP address of the client.客户机IP地址 === REMOTE_HOST === The hostname of the client.客户机hostname === REQUEST_METHOD === A string such as "GET" or "POST".请求方式,比如 GET 或 POST === SERVER_NAME === The hostname of the server. 服务器 hostname === SERVER_PORT === The port of the server. 服务器端口

user

  • 一个 django.models.auth.users.User 对象表示当前登录用户.如果当前没有用户登录, user 被设置成 django.contrib.auth.models.AnonymousUser 的一个实例.你可以用 is_anonymous() 来区分登录用户和未登录用户.就象下面这样:

   1         if request.user.is_anonymous():
   2             # Do something for anonymous users.
   3         else:
   4             # Do something for logged-in users.

session

raw_post_data

  • 原始 HTTP POST 数据. 该属性仅用于POST数据的高级处理. 更多时候你只需要 POST 对象.

方法

__getitem__(key)

  • 根据给定的键,返回一个 GET/POST 值. 该方法首先检查 POST,然后是 GET. 若给定的键未找到,引发 KeyError 异常

    有了它才允许你使用字典的访问语法来存取 HttpRequest实例. 举例来说: 无论request.POST有一个foo键还是request.GET有一个foo键,request["foo"]都会返回相应的值.

has_key()

  • 返回 True 或 False ,不必指明 request.GET 或 request.POST

get_full_path()

  • 返回一个路径,加上一个query字符串(如果有的话)
  • Example: "/music/bands/the_beatles/?print=true"

QueryDict 对象

在一个 HttpRequest 对象中, GET和POST属性都是 django.http.QueryDict 的实例. QueryDict 是一个类似字典的类,被设计成可以处理同一个键有多个值的情况.这是很必要的,因为有些 HTML 表单元素,特别是<select multiple>,使用一个键来传递多个值

QueryDict实例是不可变对象,除非你创建他们的一个拷贝.这意味着你不能直接改变 request.POST 和 request.GET 的值.

QueryDict 实现了所有的标准字典方法,因为它就是 dictionary 的一个子类.与标准方法不一致之处简略的列在下面:

__getitem__(key)

  • 返加给定键的值. 如果该键有多个值, __getitem__ 返回最后一个值

=== setitem__(key, value) ===

  • 将 key 的值设置为 [value] (一个Python 列表,只有一个元素 value).注意,这个方法象其它字典方法一个拥有副作用,只能被一个可变的QueryDict对象调用.(一个通过copy()创建的副本)

=== contains__(key) ===

  • 如果给定键存在,返回 True. 它允许你这么干: if "foo" in request.GET

=== get(key, default) ===

  • 如同 getitem__() ,如果该键不存在,返回一个默认值

has_key(key)

=== setdefault(key, default) ===

  • 类似标准字典的 setdefault(),不同之处在于它内部使用的是 setitem

=== update(other_dict) ===

  • 类似标准字典的 update() 唯一的不同是它将other_dict的元素追加到而不是替换到当前字典中
For example

          >>> q = QueryDict('a=1')
          >>> q = q.copy() # to make it mutable
          >>> q.update({'a': '2'})
          >>> q.getlist('a')
          ['1', '2']
          >>> q['a'] # returns the last
          ['2']

=== items() ===

  • 类似标准字典的 items() 方法, 类似 getitem__() 的逻辑,它使用最后一个值.

example

{{{ >>> q = QueryDict('a=1&a=2&a=3')

  • >>> q.items() [('a', '3')]}}}

=== values() ===

  • 类似标准字典的 values() 方法,类似 getitem__() 的逻辑,它使用最后一个值.

example

           >>> q = QueryDict('a=1&a=2&a=3')
           >>> q.values()
           ['3']
  • 除了这些之外,QueryDict 还拥有下列方法

=== copy() ===

  • 返回当前对象的一个拷贝,它使用标准库中的 深拷贝 方法. 这个拷贝是可变的,也就是说你可以改变这个拷贝的值.

=== getlist(key) ===

  • 以一个Python列表的形式返回指定键的值.若该键不存在,返回一个空的列表.该列表是以某种方式排序的.

=== setlist(key, list_) === 不同于 __setitem__() ,将给定的键的值设置为一个列表 === appendlist(key, item) === 将给定键对应的值(别忘了,它是一个列表)追加一个 item === setlistdefault(key, default_list) === 就象 setdefault ,不过它接受一个列表作为值而不是一个单一的值 === lists() === 就象 items(),不过它包含所有的值(以列表的方式)

           >>> q = QueryDict('a=1&a=2&a=3')
           >>> q.lists()
           [('a', ['1', '2', '3'])]

=== urlencode() === 以一个查询字符串的形式返回一个字符串

  • Example: "a=2&b=3&b=5".

例子

下面是一个例子演示了 Django 如何对待输入: {{{ <form action="/foo/bar/" method="post">

  • <input type="text" name="your_name" /> <select multiple="multiple" name="bands">

    • <option value="beatles">The Beatles</option> <option value="who">The Who</option> <option value="zombies">The Zombies</option>

    </select> <input type="submit" /> </form>

}}} 若用户输入了 "John Smith" 在 your_name 框并且选择在多选框中同时选中了 The Beatles 和 The Zombies, 然后点击 Submit, Django的request对象将拥有:

    >>> request.GET
    {}
    >>> request.POST
    {'your_name': ['John Smith'], 'bands': ['beatles', 'zombies']}
    >>> request.POST['your_name']
    'John Smith'
    >>> request.POST['bands']
    'zombies'
    >>> request.POST.getlist('bands')
    ['beatles', 'zombies']
    >>> request.POST.get('your_name', 'Adrian')
    'John Smith'
    >>> request.POST.get('nonexistent_field', 'Nowhere Man')
    'Nowhere Man'

实现备注

GET POST COOKIES FILES META REQUEST raw_post_data 和 user 属性都是惰性的.也就是说在你要求得到他们的值之前,django并不花费时间计算他们的值.只有你需要时,才实时计算出你要的值给你.简单来说,就象 xrange函数.

HttpResponse 对象

对应着 HttpRequest 对象, HttpResponse 对象也是 Django自动生成的. 该对象包含你的响应. 你写的每一个view都是可响应的并且返回一个 HttpResponse对象. HttpResponse类定义在 django.http 中.

应用

典型的应用就是将页面的内容作为字符串传递给 HpptResponse 构造函数 {{{ >>> response = HttpResponse("Here's the text of the Web page.")

  • >>> response = HttpResponse("Text only, please.", mimetype="text/plain")

}}} 如果你需要随时增加内容,你可以象使用一个文件一样来使用 response 对象. {{{ >>> response = HttpResponse()

  • >>> response.write("<p>Here's the text of the Web page.</p>") >>> response.write("<p>Here's another paragraph.</p>")

}}} 你可以使用字典语法添加或删除headers {{{ >>> response = HttpResponse()

  • >>> response['X-DJANGO'] = "It's the best." >>> del response['X-PHP'] >>> response['X-DJANGO'] "It's the best."

}}} 注意 del 不会引发 KeyError异常,即使该header 不存在.

方法

__init__(content=, mimetype=DEFAULT_MIME_TYPE)

  • 根据你提供的页面内容(一个字符串)和MIME类型,初始化一个 HttpResponse 对象.默认的MIME类型是 text/html

__setitem__(header, value)

  • header 和 value都是字符串,将给定的header设置为给定的 value

__delitem__(header)

  • 删除给定名字的header 如果header不存在,则静默.header是大小写敏感的.

__getitem__(header)

  • 返回给定header的值,大小写敏感

has_header(header)

  • 检查给定header是否存在(大小写敏感),返回 True或False.

set_cookie(key, value=, max_age=None, expires=None, path='/', domain=None, secure=None)

  • 设置一个cookie 参数与Python标准库中的 cookie Morsel 对象一样
    • max_age是一个秒数, None表示只要浏览器不关就一直存在.
    • expires 是一个这种格式的字符串: "Wdy, DD-Mon-YY HH:MM:SS GMT".

    • 如果你要设置一个跨域名的cookie,使用 domain . 举例来说: domain=".lawrence.com" 将设置一个cookie 可以被 www.lawrence.com blogs.lawrence.com 和calendars.lawrence.com 等类似的域名读取. 否则,一个cookie 只能被当前域名读取.
  • . _cookie Morsel: http://www.python.org/doc/current/lib/morsel-objects.html

delete_cookie(key)

  • 删除给定key的cookie,若该key不存在,静默

get_content_as_string(encoding)

  • 以一个Python字符串的形式返回页面内容,如果需要,将其改造为unicode对象返回.

write(content), flush() and tell()

  • 这几个方法将HttpResponse实例改造为一个类似文件的对象.

HttpResponse 子类

Django包括一系列HttpResponse子类处理不同的HTTP请求.象 HttpResponse一样,这些子类都在django.http中定义. HttpResponseRedirect

  • 该类的构造函数只接受一个参数--要重定向的路径. 该路径可以是一个 URL 全称(如 http://www.google.com) 也可以是一个不包括域名的绝对 URL (如 /search ). 注意它返回一个 HTTP 状态码 302

HttpResponsePermanentRedirect

  • 类似 HttpResponseRedirect, 不过它返回一个持久化重定向(HTTP状态码301),而不是一个 found 重定向(状态码302)

HttpResponseNotModified

  • 该类的构造函数不接受任何参数,该类表示一个页面从用户最后一次请示以来未做任何改动.

HttpResponseNotFound

HttpResponseForbidden

HttpResponseGone

HttpResponseServerError

DjangoDoc_Request_Response (last edited 2009-12-25 07:16:26 by localhost)