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

Request 和 response 对象

概述

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

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

本文档解释了 HttpRequestHttpResponse 对象的 API.

HttpRequest 对象

属性

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

path

GET

POST

REQUEST

COOKIES

FILES

META

user

   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

方法

__getitem__(key)

has_key()

get_full_path()

QueryDict 对象

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

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

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

__getitem__(key)

__setitem__(key, value)

__contains__(key)

get(key, default)

has_key(key)

setdefault(key, default)

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()

example

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

values()

example

           >>> q = `QueryDict`('a=1&a=2&a=3')
           >>> q.values()
           ['3']

copy()

getlist(key)

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()

以一个查询字符串的形式返回一个字符串

例子

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

}}} 若用户输入了 "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 对象. {{{ >>> response = HttpResponse()

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

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

方法

__init__(content=, mimetype=DEFAULT_MIME_TYPE)

__setitem__(header, value)

__delitem__(header)

__getitem__(header)

has_header(header)

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

delete_cookie(key)

get_content_as_string(encoding)

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

HttpResponse 子类

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

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