Django — view layer (request & response object, CBV and FBV, file upload)

Time:2021-1-16

1Request object of view layer

def index(request):
    '''
    request:django The encapsulated object, whose class is wsgirequest, contains all the HTTP requests
    '''
    print(request)
    print(type(request))
    # from django.core.handlers.wsgi import WSGIRequest
    #######################1 look at the previous blog
    print(request.method)
    print(request.GET)
    print(request.POST)

    ########################Get in 2 path_ full_ path,META,FIELS,body
    #Custom request header
    #The encoding method used for uploading files is form data, and the default encoding method is urlencoded
    print( request.is_ Ajax ()) # is it an Ajax request
    print( request.path )Request path
    print( request.get_ full_ Path ()) # request full path with data

    # print( request.body )The request body is binary. If the file is transferred, an error will be reported
    '''
    Using the form form, by default, the data is converted to name = lqz & password = 123 and put into the request body
    request.POST In fact, it takes the bytes format from the body and turns it into a dictionary
    requet.GET In fact, the following part of the path is disassembled and turned into a dictionary
    '''
    print( request.encoding )ා the encoding method used when the client transmits to the server

    print( request.META )Key, dictionary, a bunch of things, request user's IP address, data in request header, data of user customized request header
    '''
    Add HTTP to the key value of the request header_ And it's all capitalized
    '''
    print( request.META ['REMOTE_ Addr '], the IP address of the client
    print( request.FILES )File uploaded by client



    ########################3. Don't pay attention to it for the time being (details will be explained later)
    print( request.COOKIES )Empty dictionary
    print( request.session )Session object
    print( request.user )Anonymous users
    return HttpResponse('ok')

There are three kinds of HTTP request header and request encoding format

urlencoded
form-data
jason

 

2Response object of view layer

###Focus: the use of jsonresponse (see the source code)

def index(request):
    #Three piece set
    # return HttpResponse('ok')
    # return render(request,'index.html',context={'name':'lili','age':18})
    #Return redirect ('/ home')? To redirect your own address and a third party address. It is often used with reverse resolution

    #Return JSON format data to client
    # import json
    # res= json.dumps ({name ':'zhang San','age ': 18}, ensure_ ascii=False)
    # return HttpResponse(res)
    #The built-in jsonresponse provided by Django
    #Essence or httpresponse

    # ensure_ascii
    #Return jsonresponse ({name ':'zhang San','age ': 18}, JSON_ dumps_ params={'ensure_ ascii':False})
    #Safe: to convert formats other than dictionaries, you need safe = false
    return JsonResponse([11,12,13,'lili',[1,2,3],{'name':'lili','age':19}],safe=False)

HTTP response header encoding

Content type: text / HTML; charset = UTF-8 ᦇ the encoding type of returned data is easy to be confused: enctype encoding format (which format to put data together) is not character encoding

3CBV and FBV

CBV class base view and FBV function base view

#Write view class (or write in views.py (middle)
##The first step is to write a class and inherit view
from django.views import View

class Index(View):
    Def get (self, request): # when the URL matches successfully, the get request will be executed
        return HttpResponse('ok')

    def post(self,request):
        return HttpResponse('post')
    
##Step 2: configure routing
path('index/', views.Index.as_view()),

#In the early stage, all of them are FBV, and in the later stage, all of them are CBV

4、 The essence of CBV

 

 

#1 request came, route matching succeeded, path ('index / ', views.Index.as_ view()),
    implement views.Index.as_ view()()
#The essence is to carry out as_ View () has a closure function view ()
#The essence of 3 is view () --- dispatch ()
#4. Inside the dispatch, the def get def post in the view class is executed according to the requested method (get, post) -- >

5、 Simple file upload

#Pay attention to the encoding method in HTML


    user name:
    password:
    
    


# views.py
def index(request):
    file=request.FILES.get('myfile')
    #Open an empty file and write it
    with open(file.name,'wb') as f:
        for line in file.chunks():
            f.write(line)
    Return httpresponse ('File uploaded successfully ')