Django view-HttpRequest request object and HttpResponse response object

Article directory

  • HttpRequest
  • HttpResponse
  • practice
    • Properties and methods of the request object
    • response
def index(request): This request is actually an internally encapsulated Http request HttpRequest, which is a request object

Views in Django are mainly used to accept and respond to web requests.
The essence of a view is a function in Python
View responses are divided into two categories:
1) Return as json data (JsonResponse)
2) Return in the form of web page
2.1) Redirect to another web page (HttpResponseRedirect)
2.2) Error view (4xx, 5xx) (HttpResponseNotFound, HttpResponseForbidden, HttpResponseNotAllowed, etc.)
View response process:
Browser input -> urls route matching -> view response -> feedback to the browser
View parameters:
1) An instance of HttpRequest, usually named request
2) Parameters passed through ur1 regular expression
Location:
Usually defined in views.py under the application
Error view:
1) 404 view (page not found)
2) 400 view (customer operation error)
3) 500 views (server internal error)

HttpRequest

After receiving the Http request, the server will create an HttpRequest object based on the message.
The first parameter in the view is the HttpRequest object
After receiving the http request, the Django framework will wrap the http request into an HttpRequest object and then pass it to the view.

Request common attributes and methods
\tAttributes:
path The full path of the request
method request method, commonly used GET, POST
GET dictionary-like parameters, including all parameters of get
POST dictionary-like parameters, including all parameters of post
FILES dictionary-like parameter containing uploaded files
COOKIES dictionary, contains all COOKIES
session is like a dictionary, representing a session
META['REMOTE_ADDR']
\tmethod:
is_ajax() determines whether it is ajax(), usually used in mobile and JS
get_full_path() returns the request path including the parameter string
QueryDict: dictionary-like object
A dictionary-like data structure. The difference with the dictionary: the same key can exist.
Data acquisition method in QueryDict
dict['uname'] or dict.get('uname')
Get all the values corresponding to the specified key
dict.getlist('uname')

HttpResponse

The data returned by the server to the client
HttpResponse is created by programmers themselves
1) Instead of using a template, call HttpResponse() directly and return the HttpResponse object.
2) Call the template for rendering.
Use render
render(request, template_name[, context])
request request body object
template_name template path
context dictionary parameter, used to fill in pits

Attributes: content The returned content
charset encoding format
status_code response status code (2xx,3xx,4xx,5xx)

method:
write(xxx) write out the text directly
flush() flushes the buffer
set_cookie(key,value='xxx',max_age=None) set cookie
delete_cookie(key) delete cookie

HttpResponse subclass
HttpResponseRedirect
Response redirection: internal server jump can be realized
return HttpResponseRedict('/grade/2030')
It is recommended to use reverse analysis when using
JsonResponse
A request to return Json data, usually used in asynchronous requests
JsonResponse(dict)
When returning json data, the Content-type is application/json

Practice

Create a new project Day05DjangoPro, create an application called App


Don’t write sub-routes, just write root routes directly Day05DjangoPro\urls.py

from django.contrib import admin
from django.urls import path
from App.views import *

urlpatterns = [
    path('myrequest/',my_request),
    path('admin/', admin.site.urls),
]

App\views.py

from django.shortcuts import render, HttpResponse


# ask
def my_request(request):
    print(request) # request object
    # <WSGIRequest: GET '/myrequest/'>
    return HttpResponse('ok')

http://127.0.0.1:8000/myrequest/

The printed result is <WSGIRequest: GET ‘/myrequest/’>
What is WSGIRequest? we can take a look

WSGIRequest inherits HttpRequest. Click on HttpRequest to take a look.

QueryDict inherits from MultiValueDict, and MultiValueDict inherits from dict dictionary, so QueryDict can be used as a dictionary. QueryDict is a dictionary-like object.

Attributes and methods of the request object

App\views.py

from django.shortcuts import render, HttpResponse


# ask
def my_request(request):
    print(request) # request object
    # <WSGIRequest: GET '/myrequest/'>

    # Attributes and methods of request object
    print(request.method) #Request method, GET, POST...
    print(request.GET) # GET request parameters <QueryDict: {'name': ['Qingfeng'], 'age': ['18']}>
    print(request.GET['name']) # The first method, if not, an error will be reported
    print(request.GET.get('name', default='anonymous user')) # The second way, if not, it will return None or the default value (dict like a dictionary), no error will be reported, It is recommended to use this method
    print(request.GET.getlist('name')) # The third type, if the name has multiple values, they will all be obtained and returned in the form of a list [], and an empty list [] will be returned if there is no data
    # print(request.POST) # POST request parameters <QueryDict: {}>
    # print(request.POST.get('name', default='anonymous user')) # Same thing

    print(request.path) #The path is the route we wrote /myrequest/
    print(request.get_full_path()) #The entire path /myrequest/?age=18 & amp;name=Qingfeng & amp;name=微泫

    return HttpResponse('ok')

http://127.0.0.1:8000/myrequest/?age=18 &name=Qingfeng &name=微泫

Beside this there is…

# Request
def my_request(request):
    print(request) # request object
    print(request.COOKIES) # cookie session technology
    # {'csrftoken': 'lvQaYuMDgiemswhYomZXc1msPaoSS35J'}
    print(request.session) # session session
    # <django.contrib.sessions.backends.db.SessionStore object at 0x0000023890CB3890>
    print(request.FILES) #File, file object uploaded by the front end
    print(request.META['REMOTE_ADDR']) # Client's IP address

    return HttpResponse('ok')

Response

Day05DjangoPro\urls.py

path('myresponse/', my_response),

App\views.py

from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect, reverse, HttpResponseRedirect


def my_response(request):
    # 1. Return string: rarely used in enterprise projects
    # return HttpResponse('ok')

    # 2. Return template: used when the front and back ends are not separated
    # return render(request, 'index.html', {'key1': 'value1', 'key2': 'value2'})

    # 3. Redirect: used for page jumps and path jumps
    # redirect is the same as HttpResponseRedirect
    # return redirect("https://blog.csdn.net/weixin_59633478/category_12401835.html")
    # return redirect("/request/")
    # return HttpResponseRedirect("/request/")
    # redirect(reverse("namespace:userdetail", args=(2,)))
    # return redirect(reverse("App:userdetail", kwargs={'uid': 2}))

    # 4. Return JSON: Use when the front and back ends are separated
    return JsonResponse({<!-- -->
        'data': 123
    })


# ask
def my_request(request):
    print(request) # request object
    # <WSGIRequest: GET '/myrequest/'>

    # Attributes and methods of the request object
    # print(request.method) # Request method, GET, POST...
    # print(request.GET) # GET request parameters <QueryDict: {'name': ['Qingfeng'], 'age': ['18']}>
    # print(request.GET['name']) # The first method, if not, an error will be reported
    # print(request.GET.get('name', default='anonymous user')) # The second way, if not, it will return None or the default value (dict like a dictionary), and no error will be reported , it is recommended to use this method
    # print(request.GET.getlist('name')) # The third type, if the name has multiple values, they will all be obtained and returned in the form of a list [], and an empty list [] will be returned if there is no data
    # # print(request.POST) # POST request parameters <QueryDict: {}>
    # # print(request.POST.get('name', default='anonymous user')) # Same thing
    #
    # print(request.path) # The path is the route we wrote /myrequest/
    # print(request.get_full_path()) # Entire path /myrequest/?age=18 & amp;name=Qingfeng & amp;name=微泫

    print(request.COOKIES) # cookie session technology
    # {'csrftoken': 'lvQaYuMDgiemswhYomZXc1msPaoSS35J'}
    print(request.session) # session session
    # <django.contrib.sessions.backends.db.SessionStore object at 0x0000023890CB3890>
    print(request.FILES) #File, file object uploaded by the front end
    print(request.META['REMOTE_ADDR']) # Client's IP address

    return HttpResponse('ok')


In fact, what render returns is also HttpResponse, but we add our template, that is, html and content, through the render_to_string method. Inside it, the html content, template syntax and sent data will be combined for rendering. The content obtained after rendering is actually It is a possibly very long html data, so what is returned is also a string.

App\views.py

def my_response(request):
    response = HttpResponse('ok')
    response.content = 'hello'
    response.status_code = 400
    return response