python's Django Framework (Introduction to Django Framework, View Decorator, request Object, Response Object)

Keywords: Python Django JSON xml

12.33 Django Framework Introduction:

MVC, whose full name is Model View Controller, is a software architecture model in software engineering. It divides software system into three basic parts: Model, View and Controller. It has the advantages of low coupling, high reusability and low life cycle cost.

The design pattern of Django framework draws on the idea of MVC framework and is also divided into three parts to reduce the coupling between various parts.

The difference of Django framework is that it is divided into three parts: Model, Template and View, that is, MTV framework.

   Model: Objects responsible for business objects and databases (ORM)
   Template: Responsible for presenting pages to users
   View: Responsible for business logic and call Model and Template when appropriate

In addition, Django has a urls distributor, which distributes page requests from each URL to different view s, and then calls the corresponding Model s and Template.

12.34 View (View)

A view function (class), or view for short, is a simple Python function (class), which accepts Web requests and returns Web responses.

The response can be the HTML content of a web page, a redirect, a 404 error, an XML document, or a picture.

12.341 CBV(class base view)

urls.py:

url(r'^add_class/$', views.AddClass.as_view()),

CBV version added classes:

from django.shortcuts import HttpResponse, render, redirect
from django.views import View
from app01 import models
class AddClass(View):
    def get(self, request):
        return render(request, "add_class.html")
    def post(self, request):
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class_list/")
12.342 View Decorator

Decoration FBV:

def wrapper(func):
    def inner(*args, **kwargs):
        start_time = time.time()
        ret = func(*args, **kwargs)
        end_time = time.time()
        print("used:", end_time-start_time)
        return ret
    return inner
​
# FBV Edition Added Class
@wrapper
def add_class(request):
    if request.method == "POST":
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class_list/")
    return render(request, "add_class.html")

Decorator Decoration CBV:

The method in the class is not exactly the same as the independent function, so the function decorator can not be directly applied to the method in the class. It needs to be transformed into the method decorator first.

method_decorator decorator is provided in Django to convert function decorator into method decorator

# CBV Edition Added Class
from django.views import View
from django.utils.decorators import method_decorator
def wrapper(func):
    def inner(*args, **kwargs):
        start_time = time.time()
        ret = func(*args, **kwargs)
        end_time = time.time()
        print("used:", end_time-start_time)
        return ret
    return inner
​
#@method_decorator(wrapper, name='post')        to post Additive Decorator
#@method_decorator(wrapper, name='dispatch')    to dispatch Method decorator, equivalent to all methods under the class decorator
class AddClass(View):
    
    #http_method_names = ['get', ]                  #Customize available request methods
​
    @method_decorator(wrapper)                      #to get Method Adding Decorator
    def get(self, request):
        return render(request, "add_class.html")
​
    def post(self, request):
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class_list/")

When using CBV, we should note that dispatch() will be executed after the request comes. If batch operations are needed for specific request processing methods, such as get, post and so on, we can manually rewrite the dispatch method here. This dispatch method is the same as adding decorator on FBV.

class Login(View):
     
    def dispatch(self, request, *args, **kwargs):
        print('before')
        obj = super(Login,self).dispatch(request, *args, **kwargs)
        print('after')
        return obj
 
    def get(self,request):
        return render(request,'login.html')
 
    def post(self,request):
        print(request.POST.get('user'))
        return HttpResponse('Login.post')
12.342 request object

When a page is requested, Django creates an HttpRequest object that contains the original information of the request. Django automatically passes the object to the response view function, which is customarily accepted by the request parameter.

path_info Return the user's path to the url, excluding domain names and parameters: / music/bands/the_beatles/  
method The string representation of the HTTP method used in the request, in full capitals, "GET" and "POST"  
GET Class dictionary object containing all HTTP GET parameters  
POST Class dictionary object containing all HTTP POST parameters  
body The data of request body, request.POST of byte type, is extracted from body.  
get_full_path() Returns the path and parameters in the URL: / music/bands/the_beatles/?print=true  
12.343 Example of Uploading Files

If there are uploaded files, the form form form in the html file must be enctype="multipart/form-data"

upload_demo.html:

<body>
<h1>Django Examples of uploading files</h1>
<form action="/upload/" method="post" enctype="multipart/form-data">
    <input type="text" name="username">
    <input type="file" name="touxiang">
    <input type="submit" value="Submission">
</form>
</body>

If there is an uploaded file, views.py should take the uploaded file object from request.FILES

Server receives files: views.py

from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
def upload(request):
    if request.method == "POST":
        #print(request.POST)                    #You can only get the name of the file in the dictionary.
        #print(request.FILES)                   #Get a dictionary with file objects
        file_obj = request.FILES.get("touxiang")  #Get the file object
        #print(file_obj, type(file_obj))
        file_name = file_obj.name                # Get the filename
        with open(file_name, "wb") as f:
            for line in file_obj.chunks():       # Read data bit by bit from the uploaded file object
                f.write(line)                   # Write to a new file
        return HttpResponse("OK")
    return render(request, "upload_demo.html")
12.344 Response object

Each view needs to be instantiated, populated and returned an HttpResponse, essentially render, redirect also returns an HttpResponse object.

HttpResponse.content: Response content HttpResponse.charset: Coding of response content HttpResponse.status_code: Response status code

JsonResponse object: JsonResponse is a subclass of HttpResponse, a Django-encapsulated method for returning data in JSON format

from django.http.response import JsonResponse
def get_json_data(request):
    data = {"name": "Egon", "hobby": "Shout wheat"}
    # import json
    # return HttpResponse(json.dumps(data),content_type='application/json') 
    #Set up content_type,Browsers automatically deserialize json
    <-Equivalent to->
    # ret = HttpResponse(json.dumps(data))
    # ret['Content-type'] = 'application/json'
    # return ret
    return JsonResponse(data)
​
    #return JsonResponse([1, 2, 3, 4], safe=False)
    #JsonResponse By default, only dictionary types can be passed, if non-dictionary types need to be set safe parameter

Posted by flameche on Fri, 30 Aug 2019 07:41:51 -0700