用Django做後臺,客戶端向Django請求數據,爲了區分不同的請求,想把每個請求類別加在HTTP頭部(headers)裏面。
先做實驗,就用Python的httplib庫來做模擬客戶端,參考網上寫出模擬代碼如下:
#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/'爲服務器的響應目錄。
然後是服務端的響應代碼,《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)
運行結果如下:
$python get.py #輸出: #200 #OK #<html><body>Category is unkown, id is unkown, agent is unkown</body></html>
可以看到服務器成功響應了,但是卻沒有返回自定義的內容。
我以爲是客戶端模擬headers出問題了,查找和試驗了許多次都沒有返回正確的結果。後來去查Django的文檔,發現了相關的描述:
- 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_”的前綴,終於找到問題所在了,趕緊修改服務端代碼:
category = request.META.get('HTTP_CATEGORY', 'unkown') id = request.META.get('HTTP_ID','unkown')
果然,執行後返回了想要的結果:
$python get.py #正確的輸出: #200 #OK #<html><body>Category is Books, id is 21, agent is Super brower</body></html>
得到的經驗就是遇到問題要多查文檔,搜索引擎並不一定比文檔更高效。
.