Django learning - 3.Django's view layer

Keywords: Python Django

Project Name: mydemo2

Python version: 3.7.0

Django version: 3.2.0

Introduction to Django's View

  • The View in Django framework is a logical program used to process user requests and return responses.
  • In short, a View is a Python function or method that accepts a web request and returns a Web response.
  • No matter what logic the view itself contains, it should return a response. The response can be HTML content of the web page, redirection or 404 error, XML document or image.
  • The view layer contains two important objects: request object (request) and response object (HttpResponse).
  • The view code is usually placed in the view.py file, which is placed in the project home directory or application directory.  

1. Return a template

from django.shortcuts import render

def index(request):
    return render(request,'index.html')

2. Return to a simple view of the current time

from django.http import HttpResponse
import time

def nowtime(request):
    now=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
    html="<html><body>What's the time now%s</body><html>"%now
    return HttpResponse(html)

 

3. Return to an error page  

def error(request):
    # Directly return a 404 without loading the template page of 404
     return HttpResponseNotFound('<h1>Page not found</h1>')

    # You can directly return a status code
    # return HttpResponse(status=403)

    # Return a 404 error page
    #raise Http404("Poll does not exist")

 

 

 

  4. Redirection

Redirection is to redirect the network request to another location

from django.shortcuts import redirect
from django.urls import reverse

def resp(request):
    # Redirect redirect reverse reverse reverse resolve url address
    return redirect(reverse('nowtime'))  #Redirect to time display page

    #Execute a section of js code and redirect with js
    #Return httpresponse ('< script > alert'; location. Href = "/ nowtime"; < / script > ')

    # Load a jump page for reminder information
    # context = {'info': 'jump succeeded'}
    # return render(request, 'info.html', context)

  5. Class based basic view

views.py

from django.views import View

class MyView(View):
    def get(self, request, *args, **kwargs):
        return HttpResponse('This is a class')

myapp/urls.py

from django.urls import path,include
from . import views
from myapp.views import MyView

urlpatterns = [
    path('',views.index,name='index'),  #home page
    path('nowtime/',views.nowtime,name='nowtime'),  #current time 
    path('error/',views.error,name='error'),  #Error page
    path('resp/',views.resp,name='resp'),  #redirect
    path('class/',MyView.as_view(),name='class')  #Class based basic view
]

Where as_view() is the callable view that accepts the request and returns the response ['Get ',' post ',' put ',' patch ',' delete, 'options'.]

HttpResponse object  

  • HttpResponse(): returns text, the parameter is a string, and the text content is written in the string. If the parameter is a string containing html tags, it can also be rendered.
  • The API of HttpResponse object is defined in django.http module.
  • The HttpRequest object is automatically created by Django, and the HttpResponse object is created by the programmer.
  • Each view function must return an HttpResponse object or HttpResponse sub object.

The above examples of return template, return text and redirection have been explained. The following mainly introduces the subclasses JsonResponse and set_cookie method

1. Subclass JsonResponse

  • Return json data, which is generally used for asynchronous requests
  • Help users create JSON encoded responses
  • The default content type of JsonResponse is application/json
from django.http import JsonResponse

#Response to json data
def response_json(request):
    data=[
        {'id': 101, 'name': 'aa', 'age': 20},
        {'id': 102, 'name': 'bb', 'age': 23},
        {'id': 103, 'name': 'cc', 'age': 25},
        {'id': 104, 'name': 'dd', 'age': 27},
    ]
    return JsonResponse({'data':data})

  Note: only dictionary type data is supported in the response body, so the data list should be encapsulated into a dictionary first.

  2.set_cookie method

  • A Cookie is a small text file saved on the user's browser (client) by the Web server. It can contain information about the user.
  • The server can use the arbitrariness of the information contained in Cookies to filter and regularly maintain these information to judge the status in HTTP transmission.
  • The most typical application of Cookies is to determine whether the registered user has logged in to the website
def cookie(request):
    # Gets the current response object
    response = HttpResponse('set_cookie method')
    # Setting cookie s using response objects
    response.set_cookie('first_cookie', 'abc123')
    # Return response object
    return response

HttpRequest object  

  • After receiving the http protocol request, the server will create an HttpRequest object according to the message
  • The first argument to the view function is the HttpRequest object
  • The API of HttpRequest object is defined in django.http module

Properties (unless otherwise specified, they are read-only properties)

  • Path: a string indicating the full path of the requested page, excluding the domain name

  • Method: a string indicating the HTTP method used in the request. Common values include: 'GET' and 'POST'

  • Encoding: a string indicating the encoding method of the submitted data (this attribute is writable. You can modify it to modify the encoding used to access form data. If it is None, the default setting utf-8 is used)

  • Get: a dictionary like object that contains all the parameters of the get request method

  • Post: a dictionary like object that contains all the parameters of the post request mode

  • FILES: a dictionary like object that contains all uploaded FILES

  • COOKIES: a standard Python dictionary that contains all cookie s. Keys and values are strings

  • Session: a dictionary like object that can be read and written. It represents the current session. It is only available when Django enables session support. See "state retention" for details

method  

  • is_ajax(): returns True if the request was initiated through XMLHttpRequest

QueryDict object

  • Defined at django.http.QueryDict
  • The properties GET and POST of the request object are QueryDict objects
  • Unlike python dictionaries, objects of type QueryDict are used to handle cases where the same key has multiple values
  • Method get(): get the value according to the key

The get method can only get one value of the key. If a key has multiple values at the same time, get the last value

dict.get('key ', default), or dict [' key ']

  • Method getlist(): get the value according to the key  

You can get multiple values of a key by returning the value of the key as a list

  dict.getlist('key ', default)

Posted by akano on Sun, 24 Oct 2021 02:22:35 -0700