Request and response 对象-Django1.7

Request and response 对象

快速浏览

Django使用request and response 对象通过系统传递状态。

当请求一个页面时,Django创建一个包含关于请求的metadata(元数据)的HttpRequest对象。然后Django载入适当的view,把该HttpRequest对象作为view函数的第一个参数传递。每个view函数都返回一个HttpResponse对象。

本文档解释了HttpRequestHttpResponse对象的API,它们都被定义在django.http模块中。

HttpRequest objects

class HttpRequest
属性列表:除非另有说明,所有的属性都是只读的。session 是一个值得注意的例外。
HttpRequest.scheme 
New in Django 1.7.
一个字符串,表示request(http或https)的scheme。
HttpRequest.body
一段byte格式字符串,表示原始HTTP请求的body(主体)。在不以HTML格式(例如:图像、XML等)处理request主体时很有用。如果要作为HTML格式处理,详见HttpRequest.POST.
你也可以从一个使用类文件接口(file-like interface)的HttpRequest读取,详见HttpRequest.read().
HttpRequest.path
一个代表完整请求页路径的字符串,不包括域(domain)。例:"/music/bands/the_beatles/"
HttpRequest.path_info
在一些Web服务器的设置下,主机名后的URL被分割成了一个脚本前缀(script prefix)和一个路径信息(path info)。path_info属性总是包括路径的路径信息(path info),无论使用何种Web服务器。使用path_info属性而不是path属性可以使你的代码更容易的在测试和生产服务器之间重用。
例:如果在你的应用中WSGIScriptAlias被设置为“/minfo”,则path属性为"/minfo/music/bands/the_beatles/",path_info属性为"/music/bands/the_beatles/"。
HttpRequest.method
一个字符串,代表该request的HTTP方法。必须大写。
if request.method == 'GET':
    do_something()
elif request.method == 'POST':
    do_something_else()

HttpRequest.encoding(?)
A string representing the current encoding used to decode form submission data (or None, which means the DEFAULT_CHARSET setting is used).当连接表单数据时,你可以给该属性写内容改变 encoding 的使用。 任何后续的属性访问(像从GET和POST中读取)将使用新的encoding值。Useful if you know the form data is not in theDEFAULT_CHARSET encoding.

HttpRequest.GET

一个类字典对象,包含所用给出的HTTP GET参数。详见QueryDict

HttpRequest.POST

一个类字典对象,包含所用给出的HTTP POST参数,提供的请求包含表单数据。详见QueryDict如果你需要获得原始或request中的non-form数据,可以通过HttpRequest.body获得。

一个携带空POST字典的请求也可能通过POST。也就是说,表单需要通过POST HTTP方法但是不一定需要包含表单数据。所以,你不应该使用if request.POST检查POST方法的使用。而是if request.method == "POST"。注意:POST方法不包括文件上传的信息,详见FILES。

HttpRequest.REQUEST

从1.7版本开始弃用。使用更精准的GET和POST。...

HttpRequest.COOKIES

一个包含所有cookies的标准Python字典对象。keys和values都是字符串。

HttpRequest.FILES

一个类字典对象,包含所有的上传文件。FILES中的key等于HTML语句<input type="file" name="" />。value等于一个UploadedFile.详见Managing files

注意,如果request的方法是POST并且post数据的表单<form>含有属性enctype="multipart/form-data",FILES将包含包含数据,否则,FILES将会是一个空的类字典对象。

HttpRequest.META

一个包含所有可用的HTTP头部的标准Python字典。合适的headers根据客户端和服务器决定。

 

  • CONTENT_LENGTH – the length of the request body (as a string).
  • CONTENT_TYPE – the MIME type of the request body.
  • HTTP_ACCEPT_ENCODING – Acceptable encodings for the response.
  • HTTP_ACCEPT_LANGUAGE – Acceptable languages for the response.
  • HTTP_HOST – The HTTP Host header sent by the client.
  • 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.
  • REMOTE_HOST – The hostname of the client.
  • REMOTE_USER – The user authenticated by the Web server, if any.
  • REQUEST_METHOD – A string such as "GET" or "POST".
  • SERVER_NAME – The hostname of the server.
  • SERVER_PORT – The port of the server (as a string).

 

 例外为CONTENT_LENGTH and CONTENT_TYPE,如同上面指出的所有request中的HTTP headers都被转化成META keys,大写。用下划线代替连字符,HTTP_作为前缀。

HttpRequest.user

一个AUTH_USER_MODEL 的对象,代表当前登录的用户。如果当前没有用户登录,user将被设置成 django.contrib.auth.models.AnonymousUser的实例。你可以通过 is_authenticated()区分。

 

if request.user.is_authenticated():
    # Do something for logged-in users.
else:
    # Do something for anonymous users.

 

user只有在Django的AuthenticationMiddleware 被激活时才有用. 详见 User authentication in Django.

HttpRequest.session

是一个可读且可写的,类字典对象,代表当前的session。只用当Django支持session时才有用。详见 session documentation 。

HttpRequest.urlconf

Not defined by Django itself, but will be read if other code (e.g,a custom middleware class) sets it.如果存在,该属性会被用作当前request's root URLconf。重写ROOT_URLCONF 的设置。详见 How Django processes a request

HttpRequest.resolver_match

 

 

一个ResolverMatch的实例,代表解析的URL。该属性只在url解析发生后设置。这就意味着它在除了那些在url解析发生前执行的中间件方法 (like process_request, you can use process_view instead).,所有的view中可用。

方法列表:

HttpRequest.get_host()

返回请求中的原始主机名,按顺序,来自HTTP_X_FORWARDED_HOST (if USE_X_FORWARDED_HOST is enabled) andHTTP_HOST headers,如果你不提供值,该方法会把SERVER_NAME and SERVER_PORT的组合返回,就像 PEP 3333.Example: "127.0.0.1:8000"。

HttpRequest.get_full_path()

Returns the path, plus an appended query string, if applicable.

Example: "/music/bands/the_beatles/?print=true"

HttpRequest.build_absolute_uri(location)

Example: "http://example.com/music/bands/the_beatles/?print=true"

HttpRequest.get_signed_cookie(keydefault=RAISE_ERROR,salt=''max_age=None)

>>> request.get_signed_cookie('name')
'Tony'
>>> request.get_signed_cookie('name', salt='name-salt')
'Tony' # assuming cookie was set using the same salt
>>> request.get_signed_cookie('non-existing-cookie')
...
KeyError: 'non-existing-cookie'
>>> request.get_signed_cookie('non-existing-cookie', False)
False
>>> request.get_signed_cookie('cookie-that-was-tampered-with')
...
BadSignature: ...
>>> request.get_signed_cookie('name', max_age=60)
...
SignatureExpired: Signature age 1677.3839159 > 60 seconds
>>> request.get_signed_cookie('name', False, max_age=60)
False

HttpRequest.is_secure()

Returns True if the request is secure; that is, if it was made with HTTPS.

HttpRequest.is_ajax()

 Returns True if the request was made via an XMLHttpRequest, by checking the HTTP_X_REQUESTED_WITH header for the string'XMLHttpRequest'

HttpRequest.read(size=None)
HttpRequest.readline()
HttpRequest.readlines()
HttpRequest.xreadlines()
HttpRequest.__iter__()
方法实现一个从HttpRequest实例读取的类文件的接口。这使处理一个流形式传入的请求成为可能。

 A common use-case would be to process a big XML payload with iterative parser without constructing a whole XML tree in memory.

Given this standard interface, an HttpRequest instance can be passed directly to an XML parser such as ElementTree:

import xml.etree.ElementTree as ET
for element in ET.iterparse(request):
    process(element)

QueryDict objects

class QueryDict

Methods

............

HttpResponse objects

class HttpResponse

Usage

...........

Attributes

............

Methods

............

JsonResponse objects

New in Django 1.7.
class JsonResponse

Usage

...........

StreamingHttpResponse objects

class StreamingHttpResponse

Attributes

............

posted @ 2014-12-12 15:46  落叶落叶  阅读(646)  评论(0)    收藏  举报