-->

HttpRequest methods

By: Priya Philip 4 months ago
HttpRequest represents an incoming HTTP request, including all HTTP headers and user-submitted data

get_host()

Returns the originating host of the request using information from the HTTP_X_FORWARDED_HOST  and HTTP_HOST headers, in that order

only if USE_X_FORWARDED_HOST is enabled. 

Example: 127.0.0.1:8000

Note

The get_host() method fails when the host is behind multiple proxies.

One solution is to use middleware to rewrite the proxy headers,

as in the following example:

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()

This middleware should be positioned before any other middleware that relies on the value of get_host() – for instance, CommonMiddleware or CsrfViewMiddleware.

get_full_path()

Returns the full request string, including any query string that was provided

Example: /book/novel/popular/?print=true

build_absolute_uri(location)

Returns an absolute URI for the given location, whether that be relative or absolute.

If no location is provided, the location will be set to request.get_full_path().

If the location is already an absolute URI, it will not be altered.

Otherwise the absolute URI is built using the server variables available in this request.

Example: http://getbook.com/book/novel/popular/?print=true

get_signed_cookie()

Returns a cookie value for a signed cookie, 

or raises a django.core.signing.BadSignatureexception 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 

is_secure()Returns True if the request was made using HTTPS, False otherwise.
is_ajax()

Returns True if the request was made via an XMLHttpRequest, by checking the HTTP_X_REQUESTED_WITH header for the string “XMLHttpRequest”.

Most modern JavaScript libraries send this header.

If you write your own XMLHttpRequest call (on the browser side), you’ll have to set this header manually if you want is_ajax() to work.

If a response varies on whether or not it’s requested via AJAX and you are using some form of caching like Django’s cache middleware, you should decorate the view with vary_on_headers('HTTP_X_REQUESTED_WITH') so that the responses are properly cached.

readline()readlines()xreadlines()

xreadlines was part of the file-like object API introduced in Python 2.1 and then deprecated in Python 2.3 with the introduction of generators before being removed in Python 3.

Deprecation and change-over is straightforward and consistent with the current state of file-like objects. Probably this should have been done when Python 2.x support was dropped.

iter()

Methods implementing a file-like interface for reading from an HttpRequest instance.

This makes it possible to consume an incoming request in a streaming fashion.

A common use-case would be to process a big XML payload with iterative parser without constructing a whole XML tree in memory.

Given this standard interface, an HttpRequest instance can be passed directly to an XML parser such as ElementTree:

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

has_key(key)

Returns True if the given key was provided in the request (GET or POST). False otherwise

Comments

Let us talk!

We take the vision which comes from dreams and apply the magic of science and mathematics, adding the heritage of our profession and our knowledge to create a design.