Django obtaining parameters (path, query, request header, the request body)

First, the HTTP protocol is typically transmitted to the server There are several ways to participate:

A particular portion of the extracted URL, such as / weather / shanghai / 2018, can be a regular expression, taken in by the server route; 

query string (query string), the form key1 = value1 & key2 = value2; 

request body (body) transmitted data, such as the form data, JSON, XML; 

at http packet header (header) in a.

In 1.URL acquisition parameters

When defining URL routing, can use a regular method of obtaining expression parameters are extracted from the URL request parameters, Django extracted parameters will be passed directly to the incoming parameters view.

  1.1 unnamed parameter transfer order of definition

  Note: The order of the position parameter acquired url parameter correspondence, not interchangeable

url(r'^users/([a-z]+)/(\d{4})/$', views.get_user),
 
def get_user(request, name, ID):
    print('name=%s' % name)
    print('id=%s' % id)
    return HttpResponse('OK')

  1.2 named parameter passed by Name

  Note: If you specify the name of the parameter in the route, when receiving the parameter name, parameter name must be specified in the route of use, can not be replaced by any other name, this time, both parameter positions are interchangeable.

url(r'^users/(?P<name>[a-z]+)/(?P<id>\d{4})/$', views.users),
 
def weather(request, name, id):
    print('name=%s' % name)
    print('id=%s' % id)
    return HttpResponse('OK')

2. The query string parameters acquisition request path
(the form? K1 = v1 & k2 = v2 ), may be obtained by request.GET property returns QueryDict object.

What is QueryDict target?

Defined in django.http.QueryDict

Properties GET HttpRequest object, POST types of objects are QueryDict

Python dictionary with different types of objects QueryDict handling of the same key used with a plurality of values

  2.1 methods get (): Get value according to the key

  • If a key has multiple values ​​at the same time you will get the last value
  • If the key does not exist None value is returned, the default value may be provided for subsequent processing
dict.get ( ' Key ' , value) ==> can be abbreviated as: dict [ 'Key' ]

  All values ​​according to the key acquisition value, the value returned in a list, the specified key can be acquired: 2.2 Method GetList ()

  If the key does not exist is returned empty list [], the default value may be provided for subsequent processing

dict.getlist ( 'key', the default)

  Examples of acquisition parameters 2.3

  Access path: / user / qs / a = 1 & b = 2 & a = 3?

Note: The query string is not case-way request request, the client GET, POST method, you can get the query string data request by request.GET.

url(r'^qs/$',views.get_value,name='g_v'),
 
def get_value(request):
    a = request.GET.get('a')  #3
    b = request.GET.get('b')  #2
    num_list = request.GET.getlist('a') #['1','3']
    print(a)
    print(b)
    print(num_list)
 
    return HttpResponse(reverse('user:get_value'))

3. The request body parameters

  3.1 Form Data acquisition

  To get through request.POST

  Note: Django CSRF protection is enabled by default, will request the above manner CSRF protection verification, testing can be turned off when developing CSRF protection mechanism, commented CSRF middleware method in settings.py file

url(r'^getbody/$',views.get_body),
 
def get_body(request):
    form_data = request.POST.get('c')
    print(form_data)
    return HttpResponse(form_data)

  3.2 Non-eligible form data fetch

  Non-form volume data type of request, Django can not be resolved automatically, may acquire the most primitive data request body request.body properties, as requested analyzing their body format (JSON, XML, etc.). request.body return bytes type

JSON Import 
 
URL (R & lt '^ getJSON / $', views.get_body_json), 
 
DEF get_body_json (Request): 
    # is a binary data obtained 
    json_str = request.body 
    Print (json_str) # B '{\ n-"F": 200 is , \ n-"D": 300 \ n-\ n-} '\ 
    # binary data is decoded, decoded data json 
    json_str = json_str.decode () 
    Print (json_str) # { "F": 200 is, "D": 300 } 
    # the json data into a dictionary 
    json_data = json.loads (json_str) 
    Print (json_data) {# 'F': 200 is, 'D': 300} 
    # json data acquisition, using a dictionary mode value 
    print (json_data [ ' D ']) # 300 
    Print (json_data [' F '])               # 200
    return HttpResponse('ok')

4. For example: the Django content acquisition request header http

  Passed over by the view function reuqest, use request.META.get ( "header key") to acquire

  note:

        header key must be capitalized, the prefix must be "HTTP", if the connector is behind the dash "-" To change underscore "_." For example, your header is key to api_auth, in Django that should be used request.META.get ( "HTTP_API_AUTH") to obtain the data request header.

5. Other common object properties HttpRequest

request.method request method

request path request.path

The user object requesting request.user

request.FILES a dictionary-like object containing all uploaded files

request.encoding a string that represents the full path of the requested page does not contain the domain name or parameter.

URL (R & lt '^ otherattr / $', views.other_attr), 
 
DEF other_attr (Request): 
    Print (request.method) # the POST 
    Print (request.path) # / User / otherattr / 
    Print (request.encoding) # None: use the default settings for the browser, typically utf-8, this property is writable, 
    # can modify it to access the form encoded data used by modifying, then any access to the property will use the new encoding value.

  

 


  

Guess you like

Origin www.cnblogs.com/yblackd/p/12008536.html