Django接收自定義http header過程詳解
add by zhj: Django將所有http header(包括你自定義的http header)都放在了HttpRequest.META這個(gè)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
我個(gè)人比較喜歡跟蹤源代碼來查看,源代碼如下,
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類實(shí)例化方法__init__(self,environ)中第二個(gè)參數(shù)就是WSGIRequestHandler.get_environ()方法返回的數(shù)據(jù)
WSGIRequest.META在environ的基礎(chǔ)上加了一些鍵值對
用Django做后臺,客戶端向Django請求數(shù)據(jù),為了區(qū)分不同的請求,想把每個(gè)請求類別加在HTTP頭部(headers)里面。
先做實(shí)驗(yàn),就用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》第七章有個(gè)獲取META的例子:
# GOOD (VERSION 2)
def ua_display_good2(request):
ua = request.META.get('HTTP_USER_AGENT', 'unknown')
return HttpResponse("Your browser is %s" % ua)
正好看過這個(gè)例子,就模擬上面的這個(gè)寫了一個(gè)能夠返回客戶端自定義頭部的模塊:
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)
運(yùn)行結(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出問題了,查找和試驗(yàn)了許多次都沒有返回正確的結(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.
其中紅色的部分說明是說除了兩個(gè)特例之外,其他的頭部在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)驗(yàn)就是遇到問題要多查文檔,搜索引擎并不一定比文檔更高效。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- php的curl攜帶header請求頭信息實(shí)現(xiàn)http訪問的方法
- Golang 發(fā)送http請求時(shí)設(shè)置header的實(shí)現(xiàn)
- 對Python發(fā)送帶header的http請求方法詳解
- Python爬蟲通過替換http request header來欺騙瀏覽器實(shí)現(xiàn)登錄功能
- 理解Angular的providers給Http添加默認(rèn)headers
- java獲取http請求的Header和Body的簡單方法
- java 獲取HttpRequest Header的幾種方法(必看篇)
- HTTP中header頭部信息詳解
相關(guān)文章
python 中的list和array的不同之處及轉(zhuǎn)換問題
python中的list是python的內(nèi)置數(shù)據(jù)類型,list中的數(shù)據(jù)類不必相同的,而array的中的類型必須全部相同。這篇文章給大家介紹了python 中的list和array的不同之處及轉(zhuǎn)換問題,需要的朋友參考下吧2018-03-03
python定時(shí)任務(wù)apscheduler的詳細(xì)使用教程
APScheduler的全稱是Advanced?Python?Scheduler,它是一個(gè)輕量級的?Python定時(shí)任務(wù)調(diào)度框架,下面這篇文章主要給大家介紹了關(guān)于python定時(shí)任務(wù)apscheduler的詳細(xì)使用教程,需要的朋友可以參考下2022-02-02

