How to use the HTTP protocol to send a parameter to a server and how to get parameters in Django

Source: Internet
Author: User

Four ways to use the HTTP protocol to pass parameters to a server

    • URL path carrying parameters, shaped like/weather/beijing/2018;
    • Query string, shaped like key1=value1&key2=value2;
    • The data sent in the request body (body), such as form data, JSON, XML;
    • In the header of the HTTP message.
How Django gets parameters 1 URL Path parameter

When defining a route URL, you can use the method of extracting parameters from a regular expression to get the request parameters from the URL, and Django passes the extracted parameters directly into the view's incoming parameters.

  • unnamed parameters are passed in a defined order, such as

     url (r" ^weather/([a-z]+)/(\d{4})/$ ', Views.weather), def weather  ' city=%s '% city) print ( ' year=%s '% year) return HttpResponse ( ' OK ') 
  • Named parameters are passed by name, such as

    url(r‘^weather/(?P<city>[a-z]+)/(?P<year>\d{4})/$‘, views.weather),def weather(request, year, city): print(‘city=%s‘ % city) print(‘year=%s‘ % year) return HttpResponse(‘OK‘)
2 Querydict objects in Django

Defined in Django.http.QueryDict

HttpRequest object's properties Get, post are objects of type querydict

Unlike a Python dictionary, an object of type querydict is used to handle a condition with multiple values for the same key

    • Method Get (): Gets the value based on the key

      If a key has more than one value at a time, it gets the last value

      Returns a value of None if the key does not exist, you can set the default value for subsequent processing

      dict.get(‘键‘,默认值)可简写为dict[‘键‘]
    • Method GetList (): Gets the value from the key, the value is returned as a list, you can get all the values of the specified key

      Returns an empty list if the key does not exist [], you can set a default value for subsequent processing

      dict.getlist(‘键‘,默认值)
3. Querying string query

Gets the query string parameter in the request path (in the form of a. k1=v1&k2=v2), which can be passed by request. Gets the Querydict object that is returned by the Get property.

# /qs/?a=1&b=2&a=3def qs(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‘)

Important: The query string does not differentiate between requests, that is, if the client makes a POST request, it can still be requested. Get gets the query string data in the request.

4 Request Body

The request body data format is not fixed, can be a form type string, can be a JSON string, can be an XML string, should be treated differently.

Request body data can be sent in the form of a post, PUT, PATCH, DELETE.

4.1 Form Type Form Data

The front end sends the form type of the request body data, which can be passed by request. The Post property gets, returning the Querydict object.

def get_body(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‘)

Important: Request. Post can only be used to obtain the form of a POST request surface data.

4.2 Non-form type Non-form Data

Non-form type of request body data, Django can not automatically parse, through the Request.body property to obtain the most original request body data, the request is based on the physical (JSON, XML, etc.) to parse. Request.body returns the bytes type.

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

{"a": 1, "b": 2}

You can do this in the following ways:

import jsondef get_body_json(request): json_str = request.body json_str = json_str.decode() # python3.6 无需执行此步 req_data = json.loads(json_str) print(req_data[‘a‘]) print(req_data[‘b‘]) return HttpResponse(‘OK‘)
5 Request Header

can be obtained by request. The Meta property gets the data in the request header headers. Meta is a dictionary type.

Common request headers such as:

  • CONTENT_LENGTH, haven length of the request body (as a string).
  • CONTENT_TYPE, Haven 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, Haven HTTP Host header sent by the client.
  • HTTP_REFERER, Haven referring page, if any.
  • HTTP_USER_AGENT, Haven client ' s user-agent string.
  • QUERY_STRING, haven query string, as a single (unparsed) string.
  • REMOTE_ADDR, Haven IP Address of the client.
  • REMOTE_HOST, haven hostname of the client.
  • REMOTE_USER, Haven User authenticated by the WEB server, if any.
  • REQUEST_METHOD–a string such as "GET" or "POST" .
  • SERVER_NAME, haven hostname of the server.
  • SERVER_PORT, haven Port of the server (as a string).

Specific uses such as:

def get_headers(request): print(request.META[‘CONTENT_TYPE‘]) return HttpResponse(‘OK‘)
6 Other common HttpRequest object properties
    • Method: A string that represents the HTTP method used by the request, and the common values are: ' GET ', ' POST '.
    • User: The requested object.
    • Path: A string that represents the full path of the requested page and does not contain the domain name and Parameters section.
    • Encoding: A string that represents the encoding of the data being submitted.
      • If none is the default setting for using the browser, it is generally utf-8.
      • This property is writable and can be modified to modify the encoding used to access the form data, and then any access to the property will use the new encoding value.
    • Files: A dictionary-like object that contains all the uploaded files.

How to use the HTTP protocol to send a parameter to a server and how to get parameters in Django

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.