The Django Book

Appendix H: Request and Response Objects

闄勫綍H HTTP璇锋眰锛圧equest锛夊拰鍥炲簲锛圧esponse锛夊璞

Django uses request and response objects to pass state through the system.

Django浣跨敤request鍜宺esponse瀵硅薄鍦ㄧ郴缁熼棿浼犻掔姸鎬併

When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object.

褰撲竴涓〉闈㈣璇风ず鏃讹紝Django鍒涘缓涓涓寘鍚姹傚厓鏁版嵁鐨 HttpRequest 瀵硅薄銆 鐒跺悗Django璋冨叆鍚堥傜殑瑙嗗浘锛屾妸 HttpRequest 浣滀负瑙嗗浘鍑芥暟鐨勭涓涓弬鏁 浼犲叆銆傛瘡涓鍥捐璐熻矗杩斿洖涓涓 HttpResponse 瀵硅薄銆

Weve used these objects often throughout the book; this appendix explains the complete APIs for HttpRequest and HttpResponse objects.

鎴戜滑鍦ㄤ功涓凡缁忎娇鐢ㄨ繃杩欎簺瀵硅薄浜嗭紱杩欑瘒闄勫綍璇存槑浜 HttpRequestHttpResponse 鐨勫叏閮ˋPI銆

HttpRequest

HttpRequest瀵硅薄

HttpRequest represents a single HTTP request from some user-agent.

HttpRequest 琛ㄧず鏉ヨ嚜鏌愬鎴风鐨勪竴涓崟鐙殑HTTP璇锋眰銆

Much of the important information about the request is available as attributes on the HttpRequest instance (see Table H-1). All attributes except session should be considered read-only.

HttpRequest瀹炰緥鐨勫睘鎬у寘鍚簡鍏充簬姝ゆ璇锋眰鐨勫ぇ澶氭暟閲嶈淇℃伅(璇﹁琛℉-1)銆 闄や簡session澶栫殑鎵鏈夊睘鎬ч兘搴旇璁や负鏄彧璇荤殑.

Table H-1. Attributes of HttpRequest Objects
Attribute Description
path A string representing the full path to the requested page, not including the domain for example, "/music/bands/the_beatles/" .
method

A string representing the HTTP method used in the request. This is guaranteed to be uppercase. For example:

if request.method == 'GET':
    do_something()
elif request.method == 'POST':
    do_something_else()
GET A dictionary-like object containing all given HTTP GET parameters. See the upcoming QueryDict documentation.
POST

A dictionary-like object containing all given HTTP POST parameters. See the upcoming QueryDict documentation.

Its possible that a request can come in via POST with an empty POST dictionary if, say, a form is requested via the POST HTTP method but does not include form data. Therefore, you shouldnt use if request.POST to check for use of the POST method; instead, use if request.method == "POST" (see the method entry in this table).

Note: POST does not include file-upload information. See FILES .

REQUEST

For convenience, a dictionary-like object that searches POST first, and then GET . Inspired by PHPs $_REQUEST .

For example, if GET = {"name": "john"} and POST = {"age": '34'} , REQUEST["name"] would be "john" , and REQUEST["age"] would be "34" .

Its strongly suggested that you use GET and POST instead of REQUEST , because the former are more explicit.

COOKIES A standard Python dictionary containing all cookies. Keys and values are strings. See Chapter 12 for more on using cookies.
FILES

A dictionary-like object containing all uploaded files. Each key in FILES is the name from the <input type="file" name="" /> . Each value in FILES is a standard Python dictionary with the following three keys:

  • filename : The name of the uploaded file, as a Python string
  • content-type : The content type of the uploaded file.
  • content : The raw content of the uploaded file.

Note that FILES will contain data only if the request method was POST and the <form> that posted to the request had enctype="multipart/form-data" . Otherwise, FILES will be a blank dictionary-like object.

META

A standard Python dictionary containing all available HTTP headers. Available headers depend on the client and server, but here are some examples:

  • CONTENT_LENGTH
  • CONTENT_TYPE
  • QUERY_STRING : The raw unparsed query string
  • REMOTE_ADDR : The IP address of the client
  • REMOTE_HOST : The hostname of the client
  • SERVER_NAME : The hostname of the server.
  • SERVER_PORT : The port of the server

Any HTTP headers are available in META as keys prefixed with HTTP_ , for example:

  • HTTP_ACCEPT_ENCODING
  • HTTP_ACCEPT_LANGUAGE
  • HTTP_HOST : The HTTP Host header sent by the client
  • HTTP_REFERER : The referring page, if any
  • HTTP_USER_AGENT : The clients user-agent string
  • HTTP_X_BENDER : The value of the X-Bender header, if set
user

A django.contrib.auth.models.User object representing the currently logged-in user. If the user isnt currently logged in, user will be set to an instance of django.contrib.auth.models.AnonymousUser . You can tell them apart with is_authenticated() , like so:

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

user is available only if your Django installation has the AuthenticationMiddleware activated.

For the complete details of authentication and users, see Chapter 12.

session A readable and writable, dictionary-like object that represents the current session. This is available only if your Django installation has session support activated. See Chapter 12.
raw_post_data The raw HTTP POST data. This is useful for advanced processing.
琛 H-1. HttpRequest瀵硅薄鐨勫睘鎬
灞炴 鎻忚堪
path 琛ㄧず鎻愪氦璇锋眰椤甸潰瀹屾暣鍦板潃鐨勫瓧绗︿覆锛 涓嶅寘鎷煙鍚嶏紝濡 "/music/bands/the_beatles/"
method

琛ㄧず鎻愪氦璇锋眰浣跨敤鐨凥TTP鏂规硶銆 瀹冩绘槸澶у啓鐨勩備緥濡傦細

if request.method == 'GET':
    do_something()
elif request.method == 'POST':
    do_something_else()
GET 涓涓被瀛楀吀瀵硅薄锛屽寘鍚墍鏈夌殑HTTP鐨凣ET鍙傛暟鐨勪俊鎭 瑙 QueryDict 鏂囨。銆
POST

涓涓被瀛楀吀瀵硅薄锛屽寘鍚墍鏈夌殑HTTP鐨凱OST鍙傛暟鐨勪俊鎭 瑙 QueryDict 鏂囨。銆

閫氳繃POST鎻愪氦鐨勮姹傛湁鍙兘鍖呭惈涓涓┖鐨 POST 瀛楀吀锛 涔熷氨鏄锛 涓涓氳繃POST鏂规硶鎻愪氦鐨勮〃鍗曞彲鑳戒笉鍖呭惈鏁版嵁銆 鍥犳锛屼笉搴旇浣跨敤 if request.POST 鏉ュ垽鏂璓OST鏂规硶鐨勪娇鐢紝 鑰屾槸浣跨敤 if request.method == "POST" 锛堣琛ㄤ腑鐨 method 鏉$洰锛夈

娉ㄦ剰锛 POST 鍖呭惈鏂囦欢涓婁紶淇℃伅銆 瑙 FILES

REQUEST

涓轰簡鏂逛究鑰屽垱寤猴紝杩欐槸涓涓被瀛楀吀瀵硅薄锛屽厛鎼滅储 POST 锛 鍐嶆悳绱 GET 銆 鐏垫劅鏉ヨ嚜浜嶱HP鐨 $_REQEUST

渚嬪锛 鑻 GET = {"name": "john"}POST = {"age": '34'}REQUEST["name"] 浼氭槸 "john"REQUEST["age"] 浼氭槸 "34"

寮虹儓寤鸿浣跨敤 GETPOST 锛岃屼笉鏄 REQUEST 銆 杩欐槸涓轰簡鍚戝墠鍏煎鍜屾洿娓呮鐨勮〃绀恒

COOKIES 涓涓爣鍑嗙殑Python瀛楀吀锛屽寘鍚墍鏈塩ookie銆 閿拰鍊奸兘鏄瓧绗︿覆銆俢ookie浣跨敤鐨勬洿澶氫俊鎭绗12绔犮
FILES

涓涓被瀛楀吀瀵硅薄锛屽寘鍚墍鏈変笂浼犵殑鏂囦欢銆 FILES 鐨勯敭鏉ヨ嚜 <input type="file" name="" /> 涓殑 nameFILES 鐨勫兼槸涓涓爣鍑嗙殑Python瀛楀吀锛 鍖呭惈浠ヤ笅涓変釜閿細

  • filename 锛氬瓧绗︿覆锛岃〃绀轰笂浼犳枃浠剁殑鏂囦欢鍚嶃
  • content-type 锛氫笂浼犳枃浠剁殑鍐呭绫诲瀷銆
  • content 锛氫笂浼犳枃浠剁殑鍘熷鍐呭銆

娉ㄦ剰 FILES 鍙湪璇锋眰鐨勬柟娉曟槸 POST 锛屽苟涓旀彁浜ょ殑 <form> 鍖呭惈 enctype="multipart/form-data" 鏃 鎵嶅寘鍚暟鎹傚惁鍒欙紝 FILES 鍙槸涓涓┖鐨勭被瀛楀吀瀵硅薄銆

META

涓涓爣鍑嗙殑Python瀛楀吀锛屽寘鍚墍鏈夋湁鏁堢殑HTTP澶翠俊鎭 鏈夋晥鐨勫ご淇℃伅涓庡鎴风鍜屾湇鍔″櫒鏈夊叧銆 杩欓噷鏈夊嚑涓緥瀛愶細

  • CONTENT_LENGTH
  • CONTENT_TYPE
  • QUERY_STRING 锛氭湭瑙f瀽鐨勫師濮嬭姹傚瓧绗︿覆銆
  • REMOTE_ADDR 锛氬鎴风IP鍦板潃銆
  • REMOTE_HOST 锛氬鎴风涓绘満鍚嶃
  • SERVER_NAME 锛氭湇鍔″櫒涓绘満鍚嶃
  • SERVER_PORT 锛氭湇鍔″櫒绔彛鍙枫

META 涓湁鏁堢殑浠讳竴HTTP澶翠俊鎭兘鏄甫鏈 HTTP_ 鍓嶇紑鐨 閿紝渚嬪锛

  • HTTP_ACCEPT_ENCODING
  • HTTP_ACCEPT_LANGUAGE
  • HTTP_HOST 锛氬鎴风鍙戦佺殑 Host 澶翠俊鎭
  • HTTP_REFERER 锛氳鎸囧悜鐨勯〉闈紝濡傛灉瀛樺湪鐨勩
  • HTTP_USER_AGENT 锛氬鎴风鐨剈ser-agent瀛楃涓层
  • HTTP_X_BENDERX-Bender 澶翠俊鎭殑鍊硷紝 濡傛灉宸茶鐨勮瘽銆
user

涓涓 django.contrib.auth.models.User 瀵硅薄琛ㄧず 褰撳墠鐧诲綍鐢ㄦ埛銆 鑻ュ綋鍓嶇敤鎴峰皻鏈櫥褰曪紝 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 鏃舵湁鏁堛

鍏充簬璁よ瘉鍜岀敤鎴风殑瀹屾暣缁嗚妭锛岃绗12绔犮

session 涓涓彲璇诲啓鐨勭被瀛楀吀瀵硅薄锛岃〃绀哄綋鍓峴ession銆 浠呭綋Django宸叉縺娲籹ession鏀寔鏃舵湁鏁堛 瑙佺12绔犮
raw_post_data POST鐨勫師濮嬫暟鎹 鐢ㄤ簬瀵规暟鎹殑澶嶆潅澶勭悊銆

Request objects also have a few useful methods, as shown in Table H-2.

Request瀵硅薄鍚屾牱鍖呭惈浜嗕竴浜涙湁鐢ㄧ殑鏂规硶锛岃琛℉-2銆

Table H-2. HttpRequest Methods
Method Description
__getitem__(key)

Returns the GET/POST value for the given key, checking POST first, and then GET. Raises KeyError if the key doesnt exist.

This lets you use dictionary-accessing syntax on an HttpRequest instance.

For example, request["foo"] is the same as checking request.POST["foo"] and then request.GET["foo"] .

has_key() Returns True or False , designating whether request.GET or request.POST has the given key.
get_full_path() Returns the path , plus an appended query string, if applicable. For example, "/music/bands/the_beatles/?print=true"
is_secure() Returns True if the request is secure; that is, if it was made with HTTPS.
琛 H-2. HttpRequest 鐨勬柟娉
鏂规硶 鎻忚堪
__getitem__(key)

璇锋眰鎵缁欓敭鐨凣ET/POST鍊硷紝鍏堟煡鎵綪OST锛岀劧鍚庢槸GET銆 鑻ラ敭涓嶅瓨鍦紝鍒欏紩鍙戝紓甯 KeyError

璇ユ柟娉曚娇鐢ㄦ埛鍙互浠ヨ闂瓧鍏哥殑鏂瑰紡鏉ヨ闂竴涓 HttpRequest 瀹炰緥銆

渚嬪锛 request["foo"] 鍜屽厛妫鏌 request.POST["foo"] 鍐嶆鏌 request.GET["foo"] 涓 鏍枫

has_key() 杩斿洖 TrueFalse 锛 鏍囪瘑 request.GETrequest.POST 鏄惁鍖呭惈鎵缁欑殑 閿
get_full_path() 杩斿洖 path 锛岃嫢璇锋眰瀛楃涓叉湁鏁堬紝鍒欓檮鍔犱簬鍏跺悗銆 渚嬪锛 "/music/bands/the_beatles/?print=true"
is_secure() 濡傛灉璇锋眰鏄畨鍏ㄧ殑锛屽垯杩斿洖 True 銆 涔熷氨鏄锛岃姹傛槸浠TTPS鐨勫舰寮忔彁浜ょ殑銆

QueryDict Objects

QueryDict 瀵硅薄

In an HttpRequest object, the GET and POST attributes are instances of django.http.QueryDict . QueryDict is a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably <select multiple="multiple"> , pass multiple values for the same key.

鍦ㄤ竴涓 HttpRequest 瀵硅薄涓紝 GETPOST 灞炴ч兘鏄 django.http.QueryDict 鐨勫疄渚嬨 QueryDict 鏄竴涓被浼间簬瀛楀吀鐨勭被锛屼笓闂ㄧ敤鏉ュ鐞嗙敤涓涓敭鐨勫鍊笺傚綋澶勭悊涓浜汬TML琛ㄥ崟涓殑鍏冪礌锛岀壒鍒槸 <select multiple="multiple"> 涔嬬被浼犻掑悓涓key鐨勫鍊肩殑鍏冪礌鏃讹紝灏遍渶瑕佽繖涓被浜嗐

QueryDict instances are immutable, unless you create a copy() of them. That means you cant change attributes of request.POST and request.GET directly.

QueryDict 瀹炰緥鏄笉鍙彉鐨勶紝闄ら潪鍒涘缓浜嗕竴涓 copy() 鍓湰銆備篃灏辨槸璇翠笉鑳界洿鎺ユ洿鏀 request.POSTrequest.GET 鐨勫睘鎬с

QueryDict implements the all standard dictionary methods, because its a subclass of dictionary. Exceptions are outlined in Table H-3.

QueryDict 瀹炵幇浜嗘墍鏈夋爣鍑嗙殑瀛楀吀鐨勬柟娉曪紝鍥犱负瀹冩鏄瓧鍏哥殑涓涓瓙绫汇備笌鍏朵笉鍚岀殑涓滆タ閮藉凡鍦ㄨ〃H-3涓垪鍑恒

Table H-3. How QueryDicts Differ from StandardDictionaries.
Method Differences from Standard dict Implementation
__getitem__ Works just like a dictionary. However, if the key has more than one value, __getitem__() returns the last value.
__setitem__ Sets the given key to [value] (a Python list whose single element is value ). Note that this, as other dictionary functions that have side effects, can be called only on a mutable QueryDict (one that was created via copy() ).
get() If the key has more than one value, get() returns the last value just like __getitem__ .
update()

Takes either a QueryDict or standard dictionary. Unlike the standard dictionarys update method, this method appends to the current dictionary items rather than replacing them:

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

Just like the standard dictionary items() method, except this uses the same last-value logic as __getitem()__ :

>>> q = QueryDict('a=1&a=2&a=3')
>>> q.items()
[('a', '3')]
values() Just like the standard dictionary values() method, except this uses the same last-value logic as __getitem()__ .
琛 H-3. QueryDicts 涓庢爣鍑嗗瓧鍏哥殑鍖哄埆
鏂规硶 涓庢爣鍑嗗瓧鍏稿疄鐜扮殑涓嶅悓
__getitem__ 涓庝竴涓瓧鍏镐竴鏍枫備絾鏄紝褰撲竴涓敭鏈夊涓兼椂锛 __getitem__() 杩斿洖鏈鍚庝竴涓笺
__setitem__ 灏嗘墍缁欓敭鐨勫艰涓 [value] 锛堜竴涓彧鏈変竴涓 value 鍏冪礌鐨 Python鍒楄〃锛夈 娉ㄦ剰锛屽洜瀵瑰叾瀹冪殑瀛楀吀鍑芥暟鏈夊壇浣滅敤锛屾晠瀹冨彧鑳借绉 涓轰竴涓彲鍙樼殑 QueryDict 锛堥氳繃 copy() 鍒涘缓锛夈
get() 濡傛灉涓涓敭澶氫釜鍊硷紝鍜 __getitem__ 涓鏍凤紝 get() 杩斿洖 鏈鍚庝竴涓笺
update()
鍙傛暟鏄竴涓 QueryDict 鎴栨爣鍑嗗瓧鍏搞 鍜屾爣鍑嗗瓧鍏哥殑
update 涓嶅悓锛岃繖涓柟娉*澧炲姞*鑰屼笉鏄浛鎹竴椤瑰唴瀹癸細
>>> q = QueryDict('a=1')
>>> q = q.copy() # 浣垮叾鍙彉
>>> q.update({'a': '2'})
>>> q.getlist('a')
['1', '2']
>>> q['a'] # 杩斿洖鏈鍚庝竴涓
['2']
items()

鍜屾爣鍑嗗瓧鍏哥殑 items() 鏂规硶涓鏍凤紝 涓嶅悓鐨勬槸瀹冨拰 __getitem()__ 涓鏍凤紝杩斿洖鏈鍚庝竴涓硷細

>>> q = QueryDict('a=1&a=2&a=3')
>>> q.items()
[('a', '3')]
values() 鍜屾爣鍑嗗瓧鍏哥殑 values() 鏂规硶涓鏍凤紝 涓嶅悓鐨勬槸瀹冨拰 __getitem()__ 涓鏍凤紝杩斿洖鏈鍚庝竴涓笺

In addition, QueryDict has the methods shown in Table H-4.

鍙﹀锛 QueryDict 杩樻湁鍦ㄨ〃H-4涓垪鍑虹殑鏂规硶銆

H-4. Extra (Nondictionary) QueryDict Methods
Method Description
copy() Returns a copy of the object, using copy.deepcopy() from the Python standard library. The copy will be mutable that is, you can change its values.
getlist(key) Returns the data with the requested key, as a Python list. Returns an empty list if the key doesnt exist. Its guaranteed to return a list of some sort.
setlist(key, list_) Sets the given key to list_ (unlike __setitem__() ).
appendlist(key, item) Appends an item to the internal list associated with key .
setlistdefault(key, l) Just like setdefault , except it takes a list of values instead of a single value.
lists()

Like items() , except it includes all values, as a list, for each member of the dictionary. For example:

>>> q = QueryDict('a=1&a=2&a=3')
>>> q.lists()
[('a', ['1', '2', '3'])]
urlencode() Returns a string of the data in query-string format (e.g., "a=2&b=3&b=5" ).
琛 H-4. 闄勫姞鐨 (闈炲瓧鍏哥殑) QueryDict 鏂规硶
鏂规硶 鎻忚堪
copy() 杩斿洖涓涓璞$殑鍓湰锛屼娇鐢ㄧ殑鏄疨ython鏍囧噯搴撲腑鐨 copy.deepcopy() 銆 璇ュ壇鏈槸鍙彉鐨勶紝 涔熷氨鏄锛屼綘鑳芥敼鍙樺畠鐨勫笺
getlist(key) 浠ython鍒楄〃鐨勫舰寮忚繑鍥炴墍璇锋眰閿殑鏁版嵁銆 鑻ラ敭涓嶅瓨鍦ㄥ垯杩斿洖绌哄垪琛ㄣ 瀹冧繚璇佷簡涓瀹氫細杩斿洖鏌愮褰㈠紡鐨刲ist銆
setlist(key, list_) 灏嗘墍缁欓敭鐨勯敭鍊艰涓 list_ 锛堜笌 __setitem__() 涓嶅悓锛夈
appendlist(key, item) key 鐩稿叧鐨刲ist涓婂鍔 item
setlistdefault(key, l) setdefault 涓鏍凤紝 涓嶅悓鐨勬槸瀹冪殑绗簩涓弬鏁版槸 涓涓垪琛紝鑰屼笉鏄竴涓笺
lists()

items() 涓鏍凤紝 涓嶅悓鐨勬槸瀹冧互涓涓垪琛ㄧ殑褰㈠紡 杩斿洖瀛楀吀姣忎竴涓垚鍛樼殑鎵鏈夊笺 渚嬪锛

>>> q = QueryDict('a=1&a=2&a=3')
>>> q.lists()
[('a', ['1', '2', '3'])]
urlencode() 杩斿洖涓涓姹傚瓧绗︿覆鏍煎紡鐨勬暟鎹瓧绗︿覆 锛堝锛 "a=2&b=3&b=5" 锛夈

A Complete Example

涓涓畬鏁寸殑渚嬪瓙

For example, given this HTML form:

渚嬪, 缁欏畾杩欎釜HTML琛ㄥ崟:

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

if the user enters "John Smith" in the your_name field and selects both The Beatles and The Zombies in the multiple select box, heres what Djangos request object would have:

濡傛灉鐢ㄦ埛鍦 your_name 涓緭鍏 "John Smith" 锛屽苟涓斿湪澶氶夋涓悓鏃堕夋嫨浜員he Beatles鍜孴he Zombies锛岄偅涔堜互涓嬪氨鏄疍jango鐨剅equest瀵硅薄鎵鎷ユ湁鐨勶細

>>> 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'

Implementation Note:

浣跨敤鏃惰娉ㄦ剰:

The GET , POST , COOKIES , FILES , META , REQUEST , raw_post_data , and user attributes are all lazily loaded. That means Django doesnt spend resources calculating the values of those attributes until your code requests them.

GET , POST , COOKIES , FILES , META , REQUEST , raw_post_datauser 杩欎簺灞炴ч兘鏄欢杩熷姞杞界殑銆 涔熷氨鏄闄ら潪浠g爜涓闂畠浠紝鍚﹀垯Django骞朵笉浼氳姳璐硅祫婧愭潵璁$畻杩欎簺灞炴у笺

HttpResponse

HttpResponse

In contrast to HttpRequest objects, which are created automatically by Django, HttpResponse objects are your responsibility. Each view you write is responsible for instantiating, populating, and returning an HttpResponse .

涓嶥jango鑷姩鍒涘缓鐨 HttpRequest 瀵硅薄鐩告瘮锛 HttpResponse 瀵硅薄鍒欐槸鐢变綘鍒涘缓鐨勩 浣犲垱寤虹殑姣忎釜瑙嗗浘閮介渶瑕佸疄渚嬪寲锛屽鐞嗗拰杩斿洖涓涓 HttpResponse 瀵硅薄銆

The HttpResponse class lives at django.http.HttpResponse .

HttpResponse 绫诲瓨鍦ㄤ簬 django.http.HttpResponse

Construction HttpResponses

鏋勯燞ttpResponse

Typically, youll construct an HttpResponse to pass the contents of the page, as a string, to the HttpResponse constructor:

涓鑸儏鍐典笅锛屼綘鍒涘缓涓涓 HttpResponse 鏃讹紝浠ュ瓧绗︿覆鐨勫舰寮忔潵浼犻掗〉闈㈢殑鍐呭缁 HttpResponse 鐨勬瀯閫犲嚱鏁帮細

>>> response = HttpResponse("Here's the text of the Web page.")
>>> response = HttpResponse("Text only, please.", mimetype="text/plain")

But if you want to add content incrementally, you can use response as a filelike object:

浣嗘槸濡傛灉甯屾湜閫愭笎澧炲姞鍐呭锛屽垯鍙互鎶 response 褰撲綔涓涓被鏂囦欢瀵硅薄浣跨敤锛

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

You can pass HttpResponse an iterator rather than passing it hard-coded strings. If you use this technique, follow these guidelines:

浣犲彲浠ュ皢涓涓凯浠e櫒浼犻掔粰 HttpResponse 锛岃屼笉鏄浐瀹氱殑瀛楃涓层傚鏋滀綘瑕佽繖鏍峰仛鐨勮瘽锛岃閬靛惊浠ヤ笅瑙勫垯锛

  • The iterator should return strings.

  • 杩唬鍣ㄥ簲杩斿洖瀛楃涓层

  • If an HttpResponse has been initialized with an iterator as its content, you cant use the HttpResponse instance as a filelike object. Doing so will raise Exception .

  • 鑻ヤ竴涓 HttpResponse 宸茬粡閫氳繃瀹炰緥鍖栵紝骞朵互涓涓凯浠e櫒浣滀负鍏跺唴瀹癸紝灏变笉鑳戒互涓涓被鏂囦欢瀵硅薄浣跨敤 HttpResponse 瀹炰緥銆傝繖鏍峰仛鐨勮瘽锛屼細瀵艰嚧涓涓 Exception

Finally, note that HttpResponse implements a write() method, which makes is suitable for use anywhere that Python expects a filelike object. See Chapter 11 for some examples of using this technique.

鏈鍚庯紝娉ㄦ剰 HttpResponse 瀹炵幇浜嗕竴涓 write() 鏂规硶锛屼娇鍏跺彲浠ュ湪浠讳綍鍙互浣跨敤绫绘枃浠跺璞$殑鍦版柟浣跨敤銆 杩欐柟闈㈢殑渚嬪瓙瑙佺11绔犮

Setting Headers

璁剧疆 Headers

You can add and delete headers using dictionary syntax:

鎮ㄥ彲浠ヤ娇鐢ㄥ瓧鍏镐竴鏍峰湴娣诲姞鍜屽垹闄ゅご淇℃伅銆

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

You can also use has_header(header) to check for the existence of a header.

浣犱篃鍙互浣跨敤 has_header(header) 鏉ユ鏌ヤ竴涓ご淇℃伅椤规槸鍚﹀瓨鍦ㄣ

Avoid setting Cookie headers by hand; instead, see Chapter 12 for instructions on how cookies work in Django.

璇烽伩鍏嶆墜宸ヨ缃 Cookie 澶达紝鍙傝绗12绔燚jango涓璫ookie宸ヤ綔鍘熺悊鐨勮鏄庛

HttpResponse Subclasses

HttpResponse鐨勫瓙绫

Django includes a number of HttpResponse subclasses that handle different types of HTTP responses (see Table H-5). Like HttpResponse , these subclasses live in django.http .

Django鍖呭惈璁稿澶勭悊涓嶅悓绫诲瀷鐨凥TTP璇锋眰鐨 HttpResponse 瀛愮被锛堣琛℉-5锛夈傚儚 HttpResponse 涓鏍凤紝杩欎簺绫诲湪 django.http 涓

Table H-5. HttpResponse Subclasses
Class Description
HttpResponseRedirect The constructor takes a single argument: the path to redirect to. This can be a fully qualified URL (e.g., 'http://search.yahoo.com/' ) or an absolute URL with no domain (e.g., '/search/' ). Note that this returns an HTTP status code 302.
HttpResponsePermanentRedirect Like HttpResponseRedirect , but it returns a permanent redirect (HTTP status code 301) instead of a found redirect (status code 302).
HttpResponseNotModified The constructor doesnt take any arguments. Use this to designate that a page hasnt been modified since the users last request.
HttpResponseBadRequest Acts just like HttpResponse but uses a 400 status code.
HttpResponseNotFound Acts just like HttpResponse but uses a 404 status code.
HttpResponseForbidden Acts just like HttpResponse but uses a 403 status code.
HttpResponseNotAllowed Like HttpResponse , but uses a 405 status code. It takes a single, required argument: a list of permitted methods (e.g., ['GET', 'POST'] ).
HttpResponseGone Acts just like HttpResponse but uses a 410 status code.
HttpResponseServerError Acts just like HttpResponse but uses a 500 status code.

System Message: ERROR/3 (<string>, line 1109)

Error parsing content block for the “table” directive: exactly one table expected.

.. table:: 琛 H-5. HttpResponse 瀛愮被

    +---------------------------------+-------------------------------------------+
    |绫诲悕                             |鎻忚堪                                       |
    +=================================+===========================================+
    |``HttpResponseRedirect``         |鏋勯犲嚱鏁扮殑鍙傛暟鏈変竴涓細                     |
    |                                 |閲嶅畾鍚戠殑璺緞銆 瀹冨彲浠ユ槸涓涓畬鏁寸殑URL       |
    |                                 |锛堜緥濡傦紝 ``'http://search.yahoo.com/'`` 锛 |
    |                                 |鎴栬呬笉鍖呮嫭鍩熷悕鐨勭粷瀵硅矾寰勶紙濡               |
    |                                 |``'/search/'`` 锛夈 娉ㄦ剰瀹冭繑鍥             |
    |                                 |HTTP 鐘舵佺爜 302銆                          |
    +---------------------------------+-------------------------------------------+
    |``HttpResponsePermanentRedirect``|绫讳技 ``HttpResponseRedirect`` 锛 浣嗘槸瀹    |
    |                                 |杩斿洖涓涓案涔呴噸瀹氬悜 锛圚TTP 鐘舵佺爜 301锛夛紝     |
    |                                 |鑰屼笉鏄殏鏃舵ч噸瀹氬悜锛堢姸鎬佺爜302锛夈            |
    +---------------------------------+-------------------------------------------+
    |``HttpResponseNotModified``      |鏋勯犲嚱鏁版病鏈変换浣曞弬鏁般                     |
    |                                 |鐢ㄥ畠鏉ヨ〃绀鸿繖涓〉闈㈠湪涓婃璇锋眰鍚庢湭鏀瑰彉銆     |
    +---------------------------------+-------------------------------------------+
    |``HttpResponseBadRequest``       |绫讳技 ``HttpResponse`` 锛屼絾浣跨敤400鐘舵佺爜銆  |
    +---------------------------------+-------------------------------------------+
    |``HttpResponseNotFound``         |绫讳技 ``HttpResponse`` 锛屼絾浣跨敤404鐘舵佺爜銆  |
    +---------------------------------+-------------------------------------------+
    |``HttpResponseForbidden``        |绫讳技 ``HttpResponse`` 锛屼絾浣跨敤403鐘舵佺爜銆  |
    +---------------------------------+-------------------------------------------+
    |``HttpResponseNotAllowed``       |绫讳技 ``HttpResponse`` 锛屼絾浣跨敤405鐘舵佺爜銆  |
    |                                 |瀹冨繀椤绘湁涓涓弬鏁帮細                         |
    |                                 |鍏佽鏂规硶鐨勫垪琛ㄣ                           |
    |                                 |锛堜緥濡傦紝 ``['GET', 'POST']`` 锛夈          |
    +---------------------------------+-------------------------------------------+
    |``HttpResponseGone``             |绫讳技 ``HttpResponse`` 锛屼絾浣跨敤410鐘舵佺爜銆  |
    +---------------------------------+-------------------------------------------+
    |``HttpResponseServerError``      |绫讳技 ``HttpResponse`` 锛屼絾浣跨敤500鐘舵佺爜銆  |
    +---------------------------------+-------------------------------------------+











You can, of course, define your own HttpResponse subclass to support different types of responses not supported out of the box.

褰撶劧锛屽鏋滄鏋朵笉鏀寔涓浜涚壒鎬э紝浣犱篃鍙互瀹氫箟鑷繁鐨 HttpResponse 瀛愮被鏉ュ鐞嗕笉鍚岀殑璇锋眰銆

Returning Errors

杩斿洖閿欒

Returning HTTP error codes in Django is easy. Weve already mentioned the HttpResponseNotFound , HttpResponseForbidden , HttpResponseServerError , and other subclasses. Just return an instance of one of those subclasses instead of a normal HttpResponse in order to signify an error, for example:

鍦―jango涓繑鍥濰TTP閿欒浠g爜寰堝鏄撱傛垜浠墠闈㈠凡缁忔彁鍒 HttpResponseNotFoundHttpResponseForbiddenHttpResponseServerError 锛屽拰鍏跺畠瀛愮被銆備负浜嗘洿濂藉湴琛ㄧず涓涓敊璇紝鍙杩斿洖杩欎簺瀛愮被涔嬩竴鐨勪竴涓疄渚嬶紝鑰屼笉鏄竴涓氬父鐨 HttpResponse 锛屼緥濡傦細

def my_view(request):
    # ...
    if foo:
        return HttpResponseNotFound('<h1>Page not found</h1>')
    else:
        return HttpResponse('<h1>Page was found</h1>')

Because a 404 error is by far the most common HTTP error, theres an easier way to handle it.

鑷充粖涓烘锛404閿欒鏄渶甯歌鐨凥TTP閿欒锛屾湁涓绉嶆洿瀹规槗鐨勬柟寮忔潵澶勭悊銆

When you return an error such as HttpResponseNotFound , youre responsible for defining the HTML of the resulting error page:

褰撹繑鍥炰竴涓敊璇紝姣斿 HttpResponseNotFound 鏃讹紝闇瑕佸畾涔夐敊璇〉闈㈢殑HTML锛

return HttpResponseNotFound('<h1>Page not found</h1>')

For convenience, and because its a good idea to have a consistent 404 error page across your site, Django provides an Http404 exception. If you raise Http404 at any point in a view function, Django will catch it and return the standard error page for your application, along with an HTTP error code 404.

涓轰簡鏂逛究锛岃屼笖瀹氫箟涓涓氱敤鐨勫簲鐢ㄤ簬缃戠珯鐨404閿欒椤甸潰涔熸槸涓涓緢濂界殑閫夋嫨锛孌jango鎻愪緵浜嗕竴涓 Http404 寮傚父銆傚鏋滃湪瑙嗗浘鐨勪换浣曞湴鏂瑰紩鍙 Http404 寮傚父锛孌jango灏变細鎹曡幏閿欒骞惰繑鍥炲簲鐢ㄧ▼搴忕殑鏍囧噯閿欒椤甸潰锛屽綋鐒讹紝杩樻湁HTTP閿欒浠g爜404銆

Heres an example:

渚嬪锛

from django.http import Http404

def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})

In order to use the Http404 exception to its fullest, you should create a template that is displayed when a 404 error is raised. This template should be called 404.html , and it should be located in the top level of your template tree.

涓轰簡瀹屽叏鍙戞尌鍑 Http404 鐨勫姛鑳斤紝搴斿垱寤轰竴涓ā鏉匡紝鍦404閿欒琚紩鍙戞椂鏄剧ず銆傛ā鏉跨殑鍚嶅瓧搴旇鏄 404.html 锛岃屼笖搴旇浣嶄簬妯℃澘鏍戠殑鏈楂樺眰銆

Customizing the 404 (Not Found) View

鑷畾涔 404 (鏃犳硶鎵惧埌) 瑙嗗浘

When you raise an Http404 exception, Django loads a special view devoted to handling 404 errors. By default, its the view django.views.defaults.page_not_found , which loads and renders the template 404.html .

褰撳紩鍙 Http404 寮傚父锛孌jango鍔犺浇涓涓笓闂ㄥ鐞404閿欒鐨勮鍥俱傞粯璁ゆ儏鍐典笅锛岃繖涓鍥炬槸 django.views.defaults.page_not_found 锛屽畠浼氬姞杞藉苟鏄剧ず妯℃澘 404.html

This means you need to define a 404.html template in your root template directory. This template will be used for all 404 errors.

杩欐剰鍛崇潃闇瑕佸湪鏍规ā鏉跨洰褰曞畾涔変竴涓 404.html 妯℃澘銆傝繖涓ā鏉夸細浣滅敤浜庢墍鏈404閿欒銆

This page_not_found view should suffice for 99% of Web applications, but if you want to override the 404 view, you can specify handler404 in your URLconf, like so:

瑙嗗浘 page_not_found 閫傜敤浜99%鐨勭綉绔欏簲鐢ㄧ▼搴忥紝浣嗚嫢鏄笇鏈涢噸杞借瑙嗗浘锛屽彲浠ュ湪URLconf涓寚瀹 handler404 锛屽氨鍍忚繖鏍凤細sfas

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    ...
)

handler404 = 'mysite.views.my_custom_404_view'

Behind the scenes, Django determines the 404 view by looking for handler404 . By default, URLconfs contain the following line:

鍚庡彴鎵ц鏃讹紝Django浠 handler404 鏉ョ‘瀹404瑙嗗浘銆傞粯璁ゆ儏鍐典笅锛孶RLconf鍖呭惈浠ヤ笅鍐呭锛

from django.conf.urls.defaults import *

That takes care of setting handler404 in the current module. As you can see in django/conf/urls/defaults.py , handler404 is set to 'django.views.defaults.page_not_found' by default.

杩欏彞璇濊礋璐e綋鍓嶆ā鍧椾腑鐨 handler404 璁剧疆銆傛濡備綘鎵瑙侊紝鍦 django/conf/urls/defaults.py 涓紝 handler404 榛樿琚涓 'django.views.defaults.page_not_found'

There are three things to note about 404 views:

鍏充簬404瑙嗗浘锛屾湁涓夌偣闇瑕佹敞鎰忥細

  • The 404 view is also called if Django doesnt find a match after checking every regular expression in the URLconf.

  • 褰揇jango鍦║RLconf鏃犳硶鎵惧埌鍖归厤鐨勬鍒欒〃杈惧紡鏃讹紝404瑙嗗浘浼氭樉绀恒

  • If you dont define your own 404 view and simply use the default, which is recommended you still have one obligation: to create a 404.html template in the root of your template directory. The default 404 view will use that template for all 404 errors.

  • 濡傛灉娌℃湁瀹氫箟鑷繁鐨404瑙嗗浘锛岃屽彧鏄畝鍗曞湴浣跨敤榛樿鐨勮鍥撅紝姝ゆ椂灏遍渶瑕佸湪妯℃澘鐩綍鐨勬牴鐩綍鍒涘缓涓涓 404.html 妯℃澘銆傞粯璁ょ殑404瑙嗗浘浼氬鎵鏈404閿欒浣跨敤鏀规ā鏉裤

  • If DEBUG is set to True (in your settings module), then your 404 view will never be used, and the traceback will be displayed instead.

  • DEBUG 琚涓 True 锛堝湪settings妯″潡鍐咃級锛屽垯404瑙嗗浘涓嶄細琚娇鐢紝姝ゆ椂鏄剧ず鐨勬槸璺熻釜淇℃伅銆

Customizing the 500 (Server Error) View

鑷畾涔 500 (鏈嶅姟鍣ㄩ敊璇) 瑙嗗浘

Similarly, Django executes special-case behavior in the case of runtime errors in view code. If a view results in an exception, Django will, by default, call the view django.views.defaults.server_error , which loads and renders the template 500.html .

鍚屾牱鍦帮紝鑻ユ槸鍦ㄨ瘯鍥句唬鐮佷腑鍑虹幇浜嗚繍琛屾椂閿欒锛孌jango浼氳繘琛岀壒娈婃儏鍐靛鐞嗐傚鏋滆鍥惧紩鍙戜簡涓涓紓甯革紝Django浼氶粯璁よ闂鍥 django.views.defaults.server_error 锛屽姞杞藉苟鏄剧ず妯℃澘 500.html

This means you need to define a 500.html template in your root template directory. This template will be used for all server errors.

杩欐剰鍛崇潃闇瑕佸湪鏍规ā鏉跨洰褰曞畾涔変竴涓 500.html 妯℃澘銆傝妯℃澘浣滅敤浜庢墍鏈夋湇鍔″櫒閿欒銆

This server_error view should suffice for 99% of Web applications, but if you want to override the view, you can specify handler500 in your URLconf, like so:

瑙嗗浘 server_error 閫傜敤浜99%鐨勭綉绔欏簲鐢ㄧ▼搴忥紝浣嗚嫢鏄笇鏈涢噸杞借瑙嗗浘锛屽彲浠ュ湪URLconf涓寚瀹 handler500 锛屽氨鍍忚繖鏍凤細

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    ...
)

handler500 = 'mysite.views.my_custom_error_view'
Copyright 2006 Adrian Holovaty and Jacob Kaplan-Moss.
This work is licensed under the GNU Free Document License.
Hosting graciously provided by media temple
Chinese translate hosting by py3k.cn.