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.
鎴戜滑鍦ㄤ功涓凡缁忎娇鐢ㄨ繃杩欎簺瀵硅薄浜嗭紱杩欑瘒闄勫綍璇存槑浜 HttpRequest 鍜 HttpResponse 鐨勫叏閮ˋPI銆
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澶栫殑鎵鏈夊睘鎬ч兘搴旇璁や负鏄彧璇荤殑.
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:
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:
Any HTTP headers are available in META as keys prefixed with HTTP_ , for example:
|
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. |
灞炴 | 鎻忚堪 |
---|---|
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" 銆 寮虹儓寤鸿浣跨敤 GET 鍜 POST 锛岃屼笉鏄 REQUEST 銆 杩欐槸涓轰簡鍚戝墠鍏煎鍜屾洿娓呮鐨勮〃绀恒 |
COOKIES | 涓涓爣鍑嗙殑Python瀛楀吀锛屽寘鍚墍鏈塩ookie銆 閿拰鍊奸兘鏄瓧绗︿覆銆俢ookie浣跨敤鐨勬洿澶氫俊鎭绗12绔犮 |
FILES | 涓涓被瀛楀吀瀵硅薄锛屽寘鍚墍鏈変笂浼犵殑鏂囦欢銆 FILES 鐨勯敭鏉ヨ嚜 <input type="file" name="" /> 涓殑 name 銆 FILES 鐨勫兼槸涓涓爣鍑嗙殑Python瀛楀吀锛 鍖呭惈浠ヤ笅涓変釜閿細
娉ㄦ剰 FILES 鍙湪璇锋眰鐨勬柟娉曟槸 POST 锛屽苟涓旀彁浜ょ殑 <form> 鍖呭惈 enctype="multipart/form-data" 鏃 鎵嶅寘鍚暟鎹傚惁鍒欙紝 FILES 鍙槸涓涓┖鐨勭被瀛楀吀瀵硅薄銆 |
META | 涓涓爣鍑嗙殑Python瀛楀吀锛屽寘鍚墍鏈夋湁鏁堢殑HTTP澶翠俊鎭 鏈夋晥鐨勫ご淇℃伅涓庡鎴风鍜屾湇鍔″櫒鏈夊叧銆 杩欓噷鏈夊嚑涓緥瀛愶細
鍦 META 涓湁鏁堢殑浠讳竴HTTP澶翠俊鎭兘鏄甫鏈 HTTP_ 鍓嶇紑鐨 閿紝渚嬪锛
|
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銆
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. |
鏂规硶 | 鎻忚堪 |
---|---|
__getitem__(key) | 璇锋眰鎵缁欓敭鐨凣ET/POST鍊硷紝鍏堟煡鎵綪OST锛岀劧鍚庢槸GET銆 鑻ラ敭涓嶅瓨鍦紝鍒欏紩鍙戝紓甯 KeyError 銆 璇ユ柟娉曚娇鐢ㄦ埛鍙互浠ヨ闂瓧鍏哥殑鏂瑰紡鏉ヨ闂竴涓 HttpRequest 瀹炰緥銆 渚嬪锛 request["foo"] 鍜屽厛妫鏌 request.POST["foo"] 鍐嶆鏌 request.GET["foo"] 涓 鏍枫 |
has_key() | 杩斿洖 True 鎴 False 锛 鏍囪瘑 request.GET 鎴 request.POST 鏄惁鍖呭惈鎵缁欑殑 閿 |
get_full_path() | 杩斿洖 path 锛岃嫢璇锋眰瀛楃涓叉湁鏁堬紝鍒欓檮鍔犱簬鍏跺悗銆 渚嬪锛 "/music/bands/the_beatles/?print=true" 銆 |
is_secure() | 濡傛灉璇锋眰鏄畨鍏ㄧ殑锛屽垯杩斿洖 True 銆 涔熷氨鏄锛岃姹傛槸浠TTPS鐨勫舰寮忔彁浜ょ殑銆 |
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 瀵硅薄涓紝 GET 鍜 POST 灞炴ч兘鏄 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.POST 鍜 request.GET 鐨勫睘鎬с
QueryDict implements the all standard dictionary methods, because its a subclass of dictionary. Exceptions are outlined in Table H-3.
QueryDict 瀹炵幇浜嗘墍鏈夋爣鍑嗙殑瀛楀吀鐨勬柟娉曪紝鍥犱负瀹冩鏄瓧鍏哥殑涓涓瓙绫汇備笌鍏朵笉鍚岀殑涓滆タ閮藉凡鍦ㄨ〃H-3涓垪鍑恒
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()__ . |
鏂规硶 | 涓庢爣鍑嗗瓧鍏稿疄鐜扮殑涓嶅悓 |
---|---|
__getitem__ | 涓庝竴涓瓧鍏镐竴鏍枫備絾鏄紝褰撲竴涓敭鏈夊涓兼椂锛 __getitem__() 杩斿洖鏈鍚庝竴涓笺 |
__setitem__ | 灏嗘墍缁欓敭鐨勫艰涓 [value] 锛堜竴涓彧鏈変竴涓 value 鍏冪礌鐨 Python鍒楄〃锛夈 娉ㄦ剰锛屽洜瀵瑰叾瀹冪殑瀛楀吀鍑芥暟鏈夊壇浣滅敤锛屾晠瀹冨彧鑳借绉 涓轰竴涓彲鍙樼殑 QueryDict 锛堥氳繃 copy() 鍒涘缓锛夈 |
get() | 濡傛灉涓涓敭澶氫釜鍊硷紝鍜 __getitem__ 涓鏍凤紝 get() 杩斿洖 鏈鍚庝竴涓笺 |
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涓垪鍑虹殑鏂规硶銆
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" ). |
鏂规硶 | 鎻忚堪 |
---|---|
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" 锛夈 |
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_data 鍜 user 杩欎簺灞炴ч兘鏄欢杩熷姞杞界殑銆 涔熷氨鏄闄ら潪浠g爜涓闂畠浠紝鍚﹀垯Django骞朵笉浼氳姳璐硅祫婧愭潵璁$畻杩欎簺灞炴у笺
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 銆
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绔犮
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宸ヤ綔鍘熺悊鐨勮鏄庛
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 涓
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. |
You can, of course, define your own HttpResponse subclass to support different types of responses not supported out of the box.
褰撶劧锛屽鏋滄鏋朵笉鏀寔涓浜涚壒鎬э紝浣犱篃鍙互瀹氫箟鑷繁鐨 HttpResponse 瀛愮被鏉ュ鐞嗕笉鍚岀殑璇锋眰銆
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爜寰堝鏄撱傛垜浠墠闈㈠凡缁忔彁鍒 HttpResponseNotFound 锛 HttpResponseForbidden 锛 HttpResponseServerError 锛屽拰鍏跺畠瀛愮被銆備负浜嗘洿濂藉湴琛ㄧず涓涓敊璇紝鍙杩斿洖杩欎簺瀛愮被涔嬩竴鐨勪竴涓疄渚嬶紝鑰屼笉鏄竴涓氬父鐨 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 锛岃屼笖搴旇浣嶄簬妯℃澘鏍戠殑鏈楂樺眰銆
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瑙嗗浘涓嶄細琚娇鐢紝姝ゆ椂鏄剧ず鐨勬槸璺熻釜淇℃伅銆
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'
鍏充簬鏈瘎娉ㄧ郴缁
鏈珯浣跨敤涓婁笅鏂囧叧鑱旂殑璇勬敞绯荤粺鏉ユ敹闆嗗弽棣堜俊鎭備笉鍚屼簬涓鑸鏁寸珷鍋氳瘎娉ㄧ殑鍋氭硶锛 鎴戜滑鍏佽浣犲姣忎竴涓嫭绔嬬殑鈥滄枃鏈潡鈥濆仛璇勬敞銆備竴涓滄枃鏈潡鈥濈湅璧锋潵鏄繖鏍风殑锛
涓涓滄枃鏈潡鈥濇槸涓涓钀斤紝涓涓垪琛ㄩ」锛屼竴娈典唬鐮侊紝鎴栬呭叾浠栦竴灏忔鍐呭銆 浣犻変腑瀹冧細楂樹寒搴︽樉绀:
瑕佸鏂囨湰鍧楀仛璇勬敞锛屼綘鍙渶瑕佺偣鍑诲畠鏃佽竟鐨勬爣璇嗗潡:
鎴戜滑浼氫粩缁嗛槄璇绘瘡涓瘎璁猴紝濡傛灉鍙兘鐨勮瘽鎴戜滑涔熶細鎶婅瘎娉ㄨ冭檻鍒版湭鏉ョ殑鐗堟湰涓幓:
濡傛灉浣犳効鎰忎綘鐨勮瘎娉ㄨ閲囩敤锛岃纭繚鐣欎笅浣犵殑鍏ㄥ悕 (娉ㄦ剰涓嶆槸鏄电О鎴栫畝绉帮級
Many, many thanks to Jack Slocum; the inspiration and much of the code for the comment system comes from Jack's blog, and this site couldn't have been built without his wonderful
YAHOO.ext
library. Thanks also to Yahoo for YUI itself.