Django basics 2 - routing related

Django basics 2 - routing related

web server

The web server is also called "http web server", a type of software dedicated to providing web browsers. Common web server software: nginx, uwsgi, gunicorn, apache, tomcat, iis, etc. wsgi: Python HTTP communication technology based on CGI standard implementation asgi: async+wsgi, supports asynchronous wsgi software

routing

Routing is a one-to-one binding mapping between the URL address requested by the client and the application requested by the user (here means the view in django).

view

View function FBV

function baseview The view function must be written in the views.py file of the tie-up application

from django.http.response Import HttpResponse DEF function view name ( Request ): # Code return HttpResponse ( "return the contents" ) Copy the code

The name of the view function cannot be repeated under the same module, and the naming rule is the same as the variable naming rule

View class

class baseview

request

Limit HTTP requests

The web project runs under the http protocol, and by default it certainly supports users to send data through different http requests. Common HTTP requests

POST: add/upload
GET: get/download
PUT/PATCH: modify, where PUT means to modify the overall data, and PATCH means to modify part of the data
DELETE: delete, discard

Django supports allowing clients to access project views only through specified HTTP requests

home/views.py
, The code:

# Allow users to send POST to access the page from django.views.decorators.http Import require_http_methods @require_http_methods ( [ "POST" ] ) DEF the Login ( Request ): return HttpResponse ( "! Login success" ) Copy the code

Routing binding

demo/urls.py
, The code:

from django.contrib import admin from django.urls import path from home.views import index,index2 urlpatterns = [ path( 'admin/' , admin.site.urls), path( "index" , index), path( "login" , login), ] Copy code

The browser uses the get method to access by default, and we only support the post method, so an error will be reported. Under normal circumstances, our users can send POST or GET or PUT/PATCH by using the ajax that provides http requests in the form/js in the html web page to send POST, but now we don't have a form, so we can install a postman This software is similar to a browser but has more powerful functions than a browser. It is specially provided for developers to use for free.

Use postman to access, but due to a secure access mechanism, we need to set the demo/settings.py file

MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware' , 'django.contrib.sessions.middleware.SessionMiddleware' , 'django.middleware.common.CommonMiddleware' , #'django.middleware.csrf.CsrfViewMiddleware', # ctrl+/ ' django.contrib.auth.middleware.AuthenticationMiddleware' , 'django.contrib.messages.middleware.MessageMiddleware' , 'django.middleware.clickjacking.XFrameOptionsMiddleware' , ] Copy code

Set route binding view

In order to effectively manage the routing settings, we can put the routing back to the sub-application directory

  1. Create a routing folder under the sub-application home, generally named
    urls.py
  2. Bind the view under the sub-application home to this file
"""Sub-application routing""" from django.urls import path # During the use of routing, django provides two functions for us to bind and map urls and views, # django.urls.path # django.urls.re_path from . import views urlpatterns = [ path( 'home' , views.index), path( 'list' , views.book_list), # path("route uri address", view code) path( 'login' , views.login), ] Url view of end-user access address #: # url url = public address + the total sub-route application routing address uri copy the code
  1. In demo/urls.py in the general routing, through
    include
    Load the routing file into the Django project

demo/urls.py

"""Total routing""" from django.contrib import admin from django.urls import path,include urlpatterns = [ path( 'admin/' , admin.site.urls), # path("public url address", include("sub application directory name. routing module")) path( "book/" , include( "home.urls" )), ] Copy code

When the routing in the django project is divided into total routing and sub-application routing, then the user accesses the view, the rules for accessing the address:

http://127.0.0.1:8000/route prefix + sub-application route url address

For example: when registering the sub-application route in the total route, the route prefix is "home", then the correct address when the user visits is:

http://127.0.0.1:8000/homeindex

Of course, if the route prefix is "home/" and the url address of the sub-route is "index"
, the correct address when the user visits is:

http://127.0.0.1:8000/home/index

View receives HTTP request

In the HTTP request and response process, users often send request information to the server during the request process.

  1. Query String [Query String] The so-called query string is the data after the? On the URL address, for example: http://127.0.0.1:8000/index?name=xiaoming&pwd=123456 The above name=xiaoming&pwd=123456 is the query character The string can be obtained through request.GET. Note: GET is not an http request, that is to say, as long as there is a query string on the address, it can be obtained

  2. Request body data

  3. Request header message information

  4. upload files

Get the parameters of the query string

home/views.py

"""Query String [Query String]""" def index3 ( request ): # print(request.method) """ address: http://127.0.0.1:8000/home/index3 Printing effect: <QueryDict: {}> Analysis: The client request data obtained through request is basically saved as a QueryDict class dictionary for the view, and the above is an empty dictionary QueryDict declaration location: from django.http import QueryDict The parent class of QueryDict inherits the dict dictionary, so the method or operation provided by the dictionary, QueryDict has """ """ address: http://127.0.0.1:8000/home/index3?name=xiapming&mobile=13312345678 Printing effect: <QueryDict: {'name': ['xiapming'],'mobile': ['13312345678']}> analysis: This time, the name and mobile parameters and the value of the parameters are obtained note: Because the parameters passed by the client may have multiple values, the data values returned by the query string are all in list format """ """ address: http://127.0.0.1:8000/home/index3?name=xiapming&mobile=13312345678&lve=swimming&lve=shopping&lve=game Printing effect: <QueryDict: {'name': ['xiapming'],'mobile': ['13312345678'],'lve': ['swimming','shopping','game']}> analysis: Because lve has multiple values, the value is 3 members in the list """ """Get the parameter value in the QueryDict object""" # Get a value of the parameter, or the first value # Because QueryDict is a pseudo-dictionary object, you can get the data through get or brackets # print(request.GET .get("name")) # print(request.GET["name"]) # Get all the values of the parameters print (request.GET.getlist( "lve" )) # ['swimming','shopping','game'] print (request.GET[ 'lve' ]) # game, the following value Overwrite the previous value return HttpResponse( "ok" ) Copy code

home/urls.py:

from django.urls import path from . import views urlpatterns = [ path( "index" , views.index ), path( "index2" , views.index2 ), path( "index3" , views.index3 ), ] Copy code

Get request body data

def index4 ( request ): """Get the request body data, and the result of the data returned is QueryDict""" print (request.POST) """ Printing effect: <QueryDict: {'name': ['root'],'password': ['123456']}> """ print (request.body) # b'{\n\t"title": "\xe5\x9c\xa3\xe8\xaf\x9e\xe6\xa0\x91",\n "username":"\xe5\x9c/xa3\xe8\xaf\x9e\xe8\x80\x81\xe5\xa4\xb4",\n "age": 1200\n}' """ Printing effect: b'{\n\t"title": "\xe5\x9c\xa3\xe8\xaf\x9e\xe6\xa0\x91",\n "username":"\xe5\x9c\xa3\xe8\xaf/x9e\xe8\x80\x81\xe5\xa4\xb4",\n "age": 1200\n}' """ import json ret = json.loads(request.body) print (ret) # {'title':'Christmas tree','username':'Old Santa','age': 1200} return HttpResponse( "ok" ) Copy code

home/urls.py code:

from django.urls import path from . import views urlpatterns = [ path( "index" , views.index ), path( "index2" , views.index2 ), path( "index3" , views.index3 ), path( "index4" , views.index4 ), ] Copy code

Get request header data

def index4 ( request ): """Get request header information""" print (request.META.get( "CONTENT_TYPE" )) # application/json """Get custom request header""" print (request.META.get( "HTTP_COMPANY" ) ) # oldboyedu return HttpResponse( "ok" ) Copy code

Get uploaded files

print (request.FILES) # <MultiValueDict: {'avatar': [<InMemoryUploadedFile: Old Boy Education-Database-Storage Migration.jpg (image/jpeg)>]}> print (request.FILES.get( "avatar" ) ) # Old Boy Education-Database-Storage Migration.jpg print ( type (request.FILES.get( "avatar" ))) # <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> copy the code

response

View the corresponding data

  1. Response content

    Return data directly to the client including

    HTML content
    (Generally used for projects that do not separate the front and back ends) and
    json content
    (Development of API interface separated from front and back ends)

  2. Response page

    By returning the information of the page jump to the browser, let the browser carry out the page jump by itself

Return HTML data

ef index5(request): """Response object""" """ return HttpResponse(content="text content",content_type="content format",status="http response status code") content_type content format, default is text/html status response status code, default is 200 """ """Return html content""" return HttpResponse( "<h1>hello world</h1>" ) Copy code

Return JSON data

from django.http.response import JsonResponse import json def index5 ( request ): """Response object""" """Return json data""" # data = { # "id":1, # "username":" Zhang Xiaoming", # "money": 22.50, # "sex":True, # "lve":["swimming","walk","game"] #} # goods_list = [ # {"id":1," num":10,"name":"Product 1"}, # {"id":2,"num":10,"name":"Product 2"}, # {"id":3,"num" :10,"name":"product3"}, # {"id":4,"num":10,"name":" 4"}, #] # # Method 1, if non-dictionary data is returned, be sure Set sale=False. Return the HttpResponse # # (json.dumps (Data), the content_type = "file application/JSON") # mode # 2, if the non-return data dictionary, be sure to set the job sale = False. # Return jsonResponse (goods_list, Safe = False) Copy Code

Return picture information

def index5 ( request ): """Response object""" """The response object can not only return HTML page information, but also return plain text, or pictures, and even complete the function of file downloading [this process only needs to set content_type]""" # content = open("release.png "," RB "). Read () # return the HttpResponse (Content, the content_type =" Image/JPEG ") copy the code

Provide download support

def index5 ( request ): """Response object""" """ can also be other format data, used to provide download """ # with open("./basic-2.2.1.zip","rb" ) AS F: # reached, f.read Content = () # return the HttpResponse (Content, the content_type = "file application/X-ZIP-Compressed") copy the code

Custom response header

def index5 ( request ): """Response object""" """Set the response header in the process of returning data """ response = HttpResponse( "ok" ) # Custom response header [and attribute values can not be a multi-byte] Response [ "Company" ] = "oldboyedu" return Response copy the code

Page jump

# Jump to outside the site def index5 ( request ): """Response object""" from django.shortcuts import redirect # Method 1 # return HttpResponseRedirect("http://www.baidu.com") # Method 2 # return redirect("http://www.baidu.com") # Jump to the site def center ( request ): # Method 1 # return redirect("/student/login") # Method 2 print (reverse( "stu:user_login" )) # The route is reversed, and it is automatically resolved to the URL address according to the written view method name return redirect( reverse( "stu:user_login" )) DEF the Login ( Request ): return HttpResponse ( "landing page" ) Copy the code

When redirecting within the site, if you use reverse for route reversal analysis, you must bind the prefix and sub-route of the route in the overall route and sub-route files. The method is as follows:

# Total routing from django.contrib import admin from django.urls import path from django.urls import include urlpatterns = [ path( 'admin/' , admin.site.urls), # path('home/', include('home.urls',namespace="application alias") ), path( 'student/' , include( 'demo .student.urls' ,namespace= "stu" ) ), ] # Sub-routing documents, such as: Student/urls.py from django.urls Import path from . Import views app_name = "student" # The package name of the current sub-application urlpatterns = [ # path("index", views.index ), # path("index2", views.index2 ), # path("index3", views.index3 ), path( "center" , views.center ), path( "login" , views.login, name= "user_login" ), ] Copy code