The HttpRequest object

Remember, how many ways can you use the HTTP protocol to send parameters to the server?

  • Extracting specific parts of a URL, such as /weather/ Beijing /2018, can be intercepted using regular expressions in server-side routes;
  • Query string key1=value1&key2=value2;
  • Data sent in the body of the request, such as form data, JSON, XML;
  • In the header of an HTTP packet.

1 URL path parameters

  • If you want to get a value from a URL, you need to use grouping in a regular expression,
  • There are two ways to get a value
- Position Parameter The position of the parameter must be correct. - Keyword Parameter The position of the parameter can be changed to be the same as the keywordCopy the code
  • Note: Do not mix the two parameter methods. Only one parameter method can be used in a regular expression
  • Extract 18 188 using the above two methods to obtain URL values
http://127.0. 01.:8000/18/188/
Copy the code

Positional arguments

  • Application of urls. Py
 url(r'^(\d+)/(\d+)/$', views.index),
Copy the code
  • Function in view: The position of the argument cannot be wrong
def index(request, value1, value2) :
      # construct context
      context = {'v1':value1, 'v2':value2}
      return render(request, 'Book/index.html', context)
Copy the code

Keyword parameter

  • Application of urls. Py
- among them? The P<value1> part indicates that the name of this parameter is defined as value1 - it can be any other name.r'^(? P
      
       \d+)/(? P
       
        \d+)/$'
       
      , views.index),
Copy the code

Functions in view: The positions of arguments can be changed to match the keywords

def index(request, value2, value1) :
      # construct context
      context = {'v1':value1, 'v2':value2}
      return render(request, 'Book/index.html', context)
Copy the code

2 QueryDict objects in Django

The GET and POST attributes of the HttpRequest object are QueryDict objects

Unlike Python dictionaries, objects of type QueryDict deal with multiple values for the same key

  • Method get() : gets the value based on the key

    If a key has multiple values at the same time, the last value is retrieved

    Returns None if the key does not exist. You can set the default value for further processing

get('key', default)Copy the code
  • Method getList () : gets values by key. Values are returned as a list that can get all the values of the specified key

    If the key does not exist, the empty list [] is returned, and the default can be set for subsequent processing

getlist('key', default)Copy the code

3. Query String Query String

Gets the query string parameters in the request path (such as? K1 =v1&k2=v2), which can be obtained via the request.GET property and returns QueryDict objects.

# /get/? a=1&b=2&a=3

def get(request) :
    a = request.GET.get('a')
    b = request.GET.get('b')
    alist = request.GET.getlist('a')
    print(a)  # 3
    print(b)  # 2
    print(alist)  # (' 1 ', '3')
    return HttpResponse('OK')
Copy the code

Important: The query string does not discriminate between requests, meaning that if a client makes a POST request, the query string data in the request can still be retrieved through Request.get.

4 request body

The format of the request body data is not fixed. It can be a form string, a JSON string, or an XML string and should be treated differently.

The request body data can be sent in POST, PUT, PATCH, or DELETE modes.

Djangos CSRF protection is enabled by default and validates the above request for CSRF protection. You can disable CSRF protection during testing by commenting out the CSRF middleware in settings.py, as shown in the following example:

4.1 Form Type Form Data

The body data of form-type requests sent by the front end can be obtained using the Request. POST property and returned to QueryDict objects.

def post(request) :
    a = request.POST.get('a')
    b = request.POST.get('b')
    alist = request.POST.getlist('a')
    print(a)
    print(b)
    print(alist)
    return HttpResponse('OK')
Copy the code

4.2 Non-form Data

Django does not automatically parse non-form request body data. Instead, use the Request. body attribute to retrieve the original request body data and parse the request body data in JSON, XML, etc. Request. body returns bytes.

For example, to get the following JSON data in the request body

{"a": 1."b": 2}
Copy the code

You can perform the following operations:

import json

def post_json(request) :
    json_str = request.body
    json_str = json_str.decode()  # python3.6 This step is not required
    req_data = json.loads(json_str)
    print(req_data['a'])
    print(req_data['b'])
    return HttpResponse('OK')
Copy the code

5 request header

You can retrieve the data from the request headers using the request.META attribute, which is a dictionary type.

Common request headers are:

  • CONTENT_LENGTH — The length of The request body (as a string).
  • CONTENT_TYPE — The MIME type of The request body.
  • HTTP_ACCEPT — Acceptable content types for the response.
  • 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).

Specific use is as follows:

def get_headers(request) :
    print(request.META['CONTENT_TYPE'])
    return HttpResponse('OK')
Copy the code

6 Other common HttpRequest object attributes

  • Method: a string that indicates the HTTP method used in a request. Common values include GET and POST.
  • User: requested user object.
  • Path: A string representing the full path to the requested page, excluding the domain name and parameter parts.
  • Encoding: A string that specifies the encoding method of the submitted data.
If it isNoneThe default setting of the browser is UTF -8. This property is writable and can be modified to modify the encoding used to access the form data, and any subsequent access to the property will use the new Encoding value.Copy the code
  • FILES: a dictionary-like object that contains all uploaded FILES.