當一個web請求連接進來時,django會建立一個HttpRequest對象來封裝和保存全部請求相關的信息,而且會根據請求路由載入匹配的試圖函數,每一個請求的試圖函數都會返回一個HttpResponse對象。web
HttpRequest和HttpReponse類都包含在django.http包中ajax
HttpRequest.scheme 請求協議(http或者https) HttpRequest.body 以字節的方式返回請求體內容;能夠經過HttpRequest.POST獲取處理後的key和value,也能夠經過HttpRequest.read()格式化 HttpRequest.path 返回請求的完整路徑,不包括協議和域名 HttpRequest.GET GET請求參數,返回一個queryDict對象 HttpRequest.POST 獲取表單提交的數據,若是是經過POST請求提交的其它非表單數據,能夠使用HttpRequest.Body獲取;使用時能夠經過if request.method == "PSOT"來進行預判斷 HttpRequest.method 返回請求方式 HttpRequest.environ 返回一個字典,包含全部django運行的環境信息 HttpRequest.content_type 文件格式 HttpRequest.content_params 參數 HttpRequest.COOKIES 返回一個字典,包含瀏覽器存儲的全部cookie HttpRequest.FILES 返回一個MultiValueDict,包含上傳的文件 HttpRequest.META 返回一個包含全部請求相關信息的字典(包含Headers),同environ HttpRequest.resolver_match 返回請求處理的url及相關參數 HttpRequest.session 中間件,設置session,一個可讀可寫的字典對象 HttpRequest.get_host() 獲取請求的主機和端口 HttpRequest.get_port() 獲取端口 HttpRequest.get_full_path() 返回完整路徑,同path HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None) 獲取以一個cookie HttpRequest.is_ajax() 判斷是否爲ajax請求 HttpRequest.is_secure() 判斷是否爲https請求
HttpResponse類用於設置響應頭和響應內容,它分爲實例化對象、填充設置以及返回三個部分django
from django.http import HttpResponse # 實例化一: responseOne = HttpResponse("this is a http response")
# 實例化二: responseTwo = HttpResponse() responseTwo.write("this is another http response") responseTwo.writelines(["this is second line", "this is third line"])
# 設置響應頭 responseOne["Age"] = 20 responseOne["app"] = "sample" del responseOne["app"] # 設置響應頭 responseOne["content_type"] = 'application/vnd.ms-excel' responseOne['Content-Disposition'] = 'attachment; filename="foo.xls"' responseOne.set_cookie("date", "2018-08-21", path="/page", ) # 設置cookie responseOne.delete_cookie("date") # 刪除cookie
# 有關對象 print(responseOne) # HttpResponse print(responseOne.items()) # dict_values print(responseOne.cookies) # cookie print(responseOne.content) # 內容(字節) print(responseOne.charset) # 編碼 print(responseOne.status_code) # 狀態碼 print(responseOne.streaming) # 是否爲流 print(responseOne.closed) # 是否已發送response print(responseOne.serialize()) # 序列化響應頭和相應內容 print(responseOne.serialize_headers()) # 序列化響應頭 print(responseOne.get("Age")) # 獲取響應頭中的某個鍵值對 print(responseTwo.getvalue()) # 獲取相應的內容 # 將response設置爲流數據處理 responseTwo.readable() responseTwo.seekable() responseTwo.write("...")