您好,登錄后才能下訂單哦!
add by zhj: Django將所有http header(包括你自定義的http header)都放在了HttpRequest.META這個Python標(biāo)準(zhǔn)字典中,當(dāng)然HttpRequest.META
中還包含其它一些鍵值對,這些鍵值對是Django加進(jìn)去的,如SERVER_PORT等。對于http header,Django進(jìn)行了重命名,規(guī)則如下
(1) 所有header名大寫,將連接符“-”改為下劃線“_”
(2) 除CONTENT_TYPE和CONTENT_LENGTH,其它的header名稱前加“HTTP_”前綴
參見 https://docs.djangoproject.com/en/1.6/ref/request-response/#django.http.HttpRequest.META
我個人比較喜歡跟蹤源代碼來查看,源代碼如下,
class WSGIRequestHandler(BaseHTTPRequestHandler): server_version = "WSGIServer/" + __version__ def get_environ(self): env = self.server.base_environ.copy() env['SERVER_PROTOCOL'] = self.request_version env['REQUEST_METHOD'] = self.command if '?' in self.path: path,query = self.path.split('?',1) else: path,query = self.path,'' env['PATH_INFO'] = urllib.unquote(path) env['QUERY_STRING'] = query host = self.address_string() if host != self.client_address[0]: env['REMOTE_HOST'] = host env['REMOTE_ADDR'] = self.client_address[0] if self.headers.typeheader is None: env['CONTENT_TYPE'] = self.headers.type else: env['CONTENT_TYPE'] = self.headers.typeheader length = self.headers.getheader('content-length') if length: env['CONTENT_LENGTH'] = length for h in self.headers.headers: k,v = h.split(':',1) k=k.replace('-','_').upper(); v=v.strip() if k in env: continue # skip content length, type,etc. if 'HTTP_'+k in env: env['HTTP_'+k] += ','+v # comma-separate multiple headers else: env['HTTP_'+k] = v return env def get_stderr(self): return sys.stderr def handle(self): """Handle a single HTTP request""" self.raw_requestline = self.rfile.readline() if not self.parse_request(): # An error code has been sent, just exit return handler = ServerHandler( self.rfile, self.wfile, self.get_stderr(), self.get_environ() ) handler.request_handler = self # backpointer for logging handler.run(self.server.get_app())
class WSGIRequest(http.HttpRequest): def __init__(self, environ): script_name = base.get_script_name(environ) path_info = base.get_path_info(environ) if not path_info: # Sometimes PATH_INFO exists, but is empty (e.g. accessing # the SCRIPT_NAME URL without a trailing slash). We really need to # operate as if they'd requested '/'. Not amazingly nice to force # the path like this, but should be harmless. path_info = '/' self.environ = environ self.path_info = path_info self.path = '%s/%s' % (script_name.rstrip('/'), path_info.lstrip('/')) self.META = environ self.META['PATH_INFO'] = path_info self.META['SCRIPT_NAME'] = script_name self.method = environ['REQUEST_METHOD'].upper() _, content_params = self._parse_content_type(self.META.get('CONTENT_TYPE', '')) if 'charset' in content_params: try: codecs.lookup(content_params['charset']) except LookupError: pass else: self.encoding = content_params['charset'] self._post_parse_error = False try: content_length = int(self.environ.get('CONTENT_LENGTH')) except (ValueError, TypeError): content_length = 0 self._stream = LimitedStream(self.environ['wsgi.input'], content_length) self._read_started = False self.resolver_match = None
WSGIRequest類實例化方法__init__(self,environ)中第二個參數(shù)就是WSGIRequestHandler.get_environ()方法返回的數(shù)據(jù)
WSGIRequest.META在environ的基礎(chǔ)上加了一些鍵值對
用Django做后臺,客戶端向Django請求數(shù)據(jù),為了區(qū)分不同的請求,想把每個請求類別加在HTTP頭部(headers)里面。
先做實驗,就用Python的httplib庫來做模擬客戶端,參考網(wǎng)上寫出模擬代碼如下:
#coding=utf8 import httplib httpClient = None try: myheaders = { "category": "Books", "id": "21", 'My-Agent': "Super brower" } httpClient = httplib.HTTPConnection('10.14.1XX.XXX',8086,timeout=30) httpClient.request('GET','/headinfo/',headers=myheaders) response = httpClient.getresponse() print response.status print response.reason print response.read() except Exception, e: print e finally: if httpClient: httpClient.close()
其中'/headinfo/'為服務(wù)器的響應(yīng)目錄。
然后是服務(wù)端的響應(yīng)代碼,《The Django Book》第七章有個獲取META的例子:
# GOOD (VERSION 2) def ua_display_good2(request): ua = request.META.get('HTTP_USER_AGENT', 'unknown') return HttpResponse("Your browser is %s" % ua)
正好看過這個例子,就模擬上面的這個寫了一個能夠返回客戶端自定義頭部的模塊:
from django.http import HttpResponse def headinfo(request): category = request.META.get('CATEGORY', 'unkown') id = request.META.get('ID','unkown') agent = request.META.get('MY-AGENT','unkown') html = "<html><body>Category is %s, id is %s, agent is %s</body></html>" % (category, id, agent) return HttpResponse(html)
運行結(jié)果如下:
$python get.py #輸出: #200 #OK #<html><body>Category is unkown, id is unkown, agent is unkown</body></html>
可以看到服務(wù)器成功響應(yīng)了,但是卻沒有返回自定義的內(nèi)容。
我以為是客戶端模擬headers出問題了,查找和試驗了許多次都沒有返回正確的結(jié)果。后來去查Django的文檔,發(fā)現(xiàn)了相關(guān)的描述:
HttpRequest.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 – 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).
With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted toMETA keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.
其中紅色的部分說明是說除了兩個特例之外,其他的頭部在META字典中的key值都會被加上“HTTP_”的前綴,終于找到問題所在了,趕緊修改服務(wù)端代碼:
category = request.META.get('HTTP_CATEGORY', 'unkown') id = request.META.get('HTTP_ID','unkown')
果然,執(zhí)行后返回了想要的結(jié)果:
$python get.py #正確的輸出: #200 #OK #<html><body>Category is Books, id is 21, agent is Super brower</body></html>
得到的經(jīng)驗就是遇到問題要多查文檔,搜索引擎并不一定比文檔更高效。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。