django之HttpRequest對象


class HttpRequest [source]

屬性

所有的屬性都是只讀的,除非另有說明

HttpRequest.scheme

字符串(http/https)表示http還是https請求

HttpRequest.body

原始的http請求正文

也可以像文件一樣讀他,看 HttpRequest.read().

HttpRequest.path

完整的請求路徑,不包括域

例: "/music/bands/the_beatles/"

HttpRequest.path_info

在某些情況下,路徑被分割成腳本前綴和路徑,這樣可以使部署和測試更方便

例如腳本前綴為"/minfo", 路徑為"/minfo/music/bands/the_beatles/" path_info為 "/music/bands/the_beatles/"

HttpRequest.method

字符串(GET/POST)表示GET還是POST請求

if request.method == 'GET':
    do_something()
elif request.method == 'POST':
    do_something_else()
常用方法
HttpRequest.encoding

一個字符串,用於解碼的當前編碼的表單提交的數據(或沒有,就使用thedefault_charset)。在訪問表單數據時,可以使用此屬性來更改所用的編碼。如果你知道表格數據不是default_charset編碼。隨后的任何屬性的訪問(如閱讀從GET或POST)將使用新的encodingvalue。

HttpRequest.GET

GET請求對象,詳細查看 QueryDict 

HttpRequest.POST

POST請求對象,詳細查看 QueryDict

注意: POST不包含文件上傳,請看 FILES.

HttpRequest.COOKIES

客戶端cookies信息,字典類型

HttpRequest.FILES

一個包含所有文件對象的字典. key是<inputtype="file" name="" />中name的值,沒一個value是一個上傳的文件對象,請查看 UploadedFile.

參看 Managing files 獲取更多信息

如果要上傳文件需要在 <form> 標簽中添加 enctype="multipart/form-data",不然收到的是一個空值

HttpRequest.META

請求頭信息

例:

  • CONTENT_LENGTH 請求體當作一個字符串的總長度。
  • CONTENT_TYPE 請求體的MIME類型。
  • HTTP_ACCEPT 可以接受的內容類型的響應。
  • HTTP_ACCEPT_ENCODING 接受編碼的響應。
  • HTTP_ACCEPT_LANGUAGE 接受語言的反應。
  • HTTP_HOST 客戶端請求時用的服務端地址
  • HTTP_REFERER 參考頁面
  • HTTP_USER_AGENT 客戶端的標志信息
  • QUERY_STRING 一對一的查詢字符串
  • REMOTE_ADDR 客戶端IP
  • REMOTE_HOST 客戶端主機名
  • REMOTE_USER 客服端的身份信息
  • REQUEST_METHOD 請求方式
  • SERVER_NAME 服務器主機名
  • SERVER_PORT 服務端開放的端口

 

HttpRequest.resolver_match

An instance of ResolverMatch representing the resolved url. This attribute is only set after url resolving took place, which means it’s available in all views but not in middleware methods which are executed before url resolving takes place (like process_request, you can use process_view instead).

應用代碼設置的屬性

Django本身不設置這些屬性,可以被服務端設置的屬性

HttpRequest.current_app
Django 1.8后新屬性

The url template tag will use its value as the current_app argument to reverse().

HttpRequest.urlconf

This will be used as the root URLconf for the current request, overriding the ROOT_URLCONF setting. See How Django processes a request for details.

urlconf can be set to None to revert any changes made by previous middleware and return to using theROOT_URLCONF.

Changed in Django 1.9:

Setting urlconf=None raised ImproperlyConfigured in older versions.

被中間件設置的屬性

Django項目中要求包含這些中間件,如果請求中看不到這些屬性, 查看下這些中間件列表 MIDDLEWARE_CLASSES.

HttpRequest.session

來自 SessionMiddleware中間件:一個可讀寫類似字典對象的當前會話

HttpRequest.site

來自 CurrentSiteMiddleware中間件: An instance of Site or RequestSite as returned byget_current_site() representing the current site.

HttpRequest.user

來是 AuthenticationMiddleware中間件: An instance of AUTH_USER_MODEL representing the currently logged-in user. If the user isn’t currently logged in, user will be set to an instance of 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. 

方法

HttpRequest.get_host() [source]

返回從HTTP_X_FORWARDED_HOST (ifUSE_X_FORWARDED_HOST is enabled)和HTTP_HOST headers獲取的主機名和端口信息像PEP 3333的格式

例: "127.0.0.1:8000"

注意:

 get_host() 獲取失敗,說明后面有很多代理. 一個解決方案是使用中間件來重寫代理頭文件,如下面的例子:

class MultipleProxyMiddleware(object):
    FORWARDED_FOR_FIELDS = [
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED_HOST',
        'HTTP_X_FORWARDED_SERVER',
    ]

    def process_request(self, request):
        """
        Rewrites the proxy headers so that only the most
        recent proxy is used.
        """
        for field in self.FORWARDED_FOR_FIELDS:
            if field in request.META:
                if ',' in request.META[field]:
                    parts = request.META[field].split(',')
                    request.META[field] = parts[-1].strip()
View Code

該中間就被其他中間件需要get_host()獲取值的中間就依賴 – 例如, CommonMiddleware or CsrfViewMiddleware.

HttpRequest.get_port() [source]
Django 1.9新的

返回包含HTTP_X_FORWARDED_PORT (ifUSE_X_FORWARDED_PORT is enabled) 和 SERVER_PORT META 的值

HttpRequest.get_full_path() [source]

返回包含路徑和查詢字符串的路徑

例: "/music/bands/the_beatles/?print=true"

HttpRequest.build_absolute_uri(location) [source]

返回一個絕對的url地址

例如: "https://example.com/music/bands/the_beatles/?print=true"

注意:

如果混合了http和https是獲取不准確的,除非全部重定向到https

Returns a cookie value for a signed cookie, or raises a django.core.signing.BadSignature exception if the signature is no longer valid. If you provide the default argument the exception will be suppressed and that default value will be returned instead.

The optional salt argument can be used to provide extra protection against brute force attacks on your secret key. If supplied, the max_age argument will be checked against the signed timestamp attached to the cookie value to ensure the cookie is not older than max_age seconds.

For example:

>>> request.get_signed_cookie('name')
'Tony'
>>> request.get_signed_cookie('name', salt='name-salt')
'Tony' # assuming cookie was set using the same salt
>>> request.get_signed_cookie('non-existing-cookie')
...
KeyError: 'non-existing-cookie'
>>> request.get_signed_cookie('non-existing-cookie', False)
False
>>> request.get_signed_cookie('cookie-that-was-tampered-with')
...
BadSignature: ...
>>> request.get_signed_cookie('name', max_age=60)
...
SignatureExpired: Signature age 1677.3839159 > 60 seconds
>>> request.get_signed_cookie('name', False, max_age=60)
False
View Code

See cryptographic signing for more information.

HttpRequest.is_secure() [source]

返回是否是https請求

HttpRequest.is_ajax() [source]

返回是否是異步請求

HttpRequest.read(size=None) [source]
HttpRequest.readline() [source]
HttpRequest.readlines() [source]
HttpRequest.xreadlines() [source]
HttpRequest.__iter__()

再處理XML是,如果數據量過大,使用可迭代的傳入請求數據,而不是完整的讀取

使用這個標准的接口, 把數據傳入ElementTree:

import xml.etree.ElementTree as ET for element in ET.iterparse(request): process(element)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM