Django handles the request flow

Djangos simple instructions

1. Install

  • pip install django

2. Create projects

  • The directory structure
├ ─ ─ the demo# Project Catalog│ ├ ─ ─ just set pySign # package│ ├ ─ ─ Settings. Py# Project profile│ ├ ─ ─ urls. Py# Route mapping table│ └ ─ ─ wsgi. Py# wsgi interface└ ─ ─ the manage. Py# project management commands
Copy the code
  • Manage. py is a command-line tool used by Django to manage this project, run the site, automate database generation, and so on.
  • Python manage.py startApp app Creates your own application
  • Add your app to INSTALLED_APPS in settings.py
  • Python manage.py runServer starts the service
  • Access to 127.0.0.1:8000

3. The Settings file

# 项目根目录
BASE_DIR = Path(__file__).resolve().parent.parent

# 调试模式
DEBUG = True


# 允许访问的主机
ALLOWED_HOSTS = ['*']

# 安装的app,自己创建的app也应该加入
INSTALLED_APPS

# 模板配置
TEMPLATES

# 数据库配置,支持sqlite、mysql、oracle、pg
DATABASE=

#语⾔编码
LANGUAGE_CODE = 'zh-hans' 

#时区
TIME_ZONE = 'Asia/Shanghai' 
Copy the code

Simple view

  • The views.py in the app represents the view, accepts the user request, and returns the text, HTML, and redirection to the client after processing the logic
from django.http import HttpResponse


def index(request) :
    return HttpResponse("index view")
Copy the code

Simple routing

  • Once you define the view, you also need to match the request path to the view and create a urls.py file in your app’s application directory
from django.urls import path
from .views import index

urlpatterns = [
    path('index/', index, name="index"),
]
Copy the code
  • Urlpatterns is a fixed name and should not be changed
  • The first argument to the path function is the pathname. The second argument is the view function. The name argument is used to map the name to the path.
  • Even if you add the configuration in urls.py, you still cannot access it. You need to import urls.py from app to urls.py from project directory
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('app.urls'))
]
Copy the code
  • You can access urls under your app using the API path prefix
  • Note that the API is not preceded by a slash
  • Visit http://127.0.0.1:8000/api/index/ can see write their own view

Simple template

  • Goal: Return a page
  • Create the index.html file under Templates
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <h2>this is index page</h2> </body> </html>Copy the code
  • Modify views.py
from django.shortcuts import render


def index(request):
    return render(request, "index.html")
Copy the code
  • The request argument is necessary because the framework encapsulates the request as a Request object and passes it as a parameter

A simple model

  • Define model classes in the models.py file. A model class is equivalent to a table
class User(models.Model):
    uname = models.CharField(max_length=20)
    password = models.CharField(max_length=32)
Copy the code
  • Run Python manage.py migrate

  • Run python manage.py Makemigrations

  • Run Python manage.py migrate

  • Description: Run Python Manage. py Migrate for the first time, and generate tables required by the Django framework. Python Manage. py Makemigbar Database migration files, and record information about tables generated. The second python manage.py Migrate will actually generate a custom database

  • Create two pieces of data

  • Create a view
def users(request):
    users = User.objects.all()
    return render(request, "users.html", context={"users", users})
Copy the code
  • Add the routing
path('users/', users, name="users")
Copy the code
  • Access to 127.0.0.1:8000 / API/users

routing

Path function argument

  • Path name
  • The view function
  • Kwargs This parameter is optional
  • Name: Use this name to query the path name in reverse order

1. Path name

  • In addition to the specific path name, you can also write regular expressions to strictly request the path
re_path('re/(\d{11})', re_view, name="re")
Copy the code
  • Assume that the path above matches the phone number
def re_view(request, phone):
    return HttpResponse(phone)
Copy the code
  • Add a handler function to the view

  • Conclusion:
    • Path matching in urls.py matches from top to bottom

    • A view can have multiple request paths

    • Do not start the path with a slash

    • If the path does not match, a 404 error will be reported. Setting Settings. Py DEBUG=False will call the default error view

Dynamic urls

path("hello/<name>/",views.hello)

path("show/<name>/<int:age>",views.show)
Copy the code
  • When enclosing variables with <>, the view function must use the same variable name
def foo(request, name):
    pass
Copy the code
  • Int :age is the same as above, but also defines that the variable is of type int
  • The parameter types
    • STR: defaults to STR if not defined
    • Int: matches 0 and positive integers
    • Slug: a string consisting of letters, digits, hyphens, and underscores
    • Path: matches a non-empty string

The path / < path: the path > : suppose there is a path name, when the request 127:0.0.1:8000 / path/etc/a/b/c, will pass the/etc/a/b/c string to view

Re_path (r '^ hello/(\ w +)/(\ d {1, 2}) / $', views. Hello) re_path (r' ^ hello/(? P<name>\w+)/(? P < age > \ d {1, 2}) / $', views. Hello,Copy the code
  • The () part is a group of re’s that are passed to the view function when a match is made
  • Re_path (r ‘^ hello/(\ w +)/(\ d {1, 2}) / $’, views. Hello) (\ w +) is in the position parameter, view function in arbitrary variable names can be accepted
def foo(request, value1, value2):
    pass
Copy the code
  • re_path(r’^hello/(? P

    \w+)/(? P

    \d{1,2})/$’,views.hello) : the view function can only be name and age

def foo(request, name, age):
    pass
Copy the code

Request and response objects

1. HttpRequest object

  • An object that the server encapsulates after receiving a request
  • The first object of the attempted function must be an HttpRequest object
  • HttpRequest Information available
attribute instructions
content-type Mime type of the request
GET A QUeryDict object that contains all the parameters of the get request, i.e.? After the content of the
POST A QUeryDict object that contains all the arguments to post
COOKIES A standard Python dictionary that contains all cookies
SESSION A dictionary-like object that represents the current session, available only if Django has a session enabled
PATH A string representing the full path of the request, excluding the domain name
method A string representing the common HTTP methods, GET and POST
FILES A QueryDict that contains all uploaded files
META Request header information
scheme agreement
  • Common key values in META
key instructions
HTTP_REFERER Source page
REMOTE_ADDR The client IP
REMOTE_HOST Client host
  • Commonly used method
The method name instructions
get_host() Host + Port
get_full_path() Gets the request path + query string
is_ajax() Ajax requests return True
build_absolute_uri() Full url

QueryDict

  • QueryDict is a subclass of Dict, and the biggest difference is that the values are lists. QueryDict is used to store parameters passed in from a request, such as multi-valued parameters like SELECT and checkbox on a form. Get, POST, and Files requests all correspond to a QueryDict

  • QueryDict in HttpRequest is immutable and can only be retrieved, not modified

  • QueryDict key-value pairs are strings

  • QueryDict can have multiple values for a single key

  • The sample

{' hobby ': [' basketball', 'play', 'k song],' name ': [' Tom'], 'age' : '21'}Copy the code
  • In actual combat
urlpatterns = [
    path('req_test/', req_test, name="req_test"),
]
Copy the code
  • Defining view functions
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>demo</title> </head> <body> <h2>name {{ name }}</h2>  <h2>hobby {{ hobbies }}</h2> <h2>host {{ host }}</h2> <h2>full_path {{ full_path }}</h2> <h2>absolute_uri {{ absolute_uri }}</h2> <h2>remote_address {{ remote_address }}</h2> <h2>REMOTE_HOST {{ REMOTE_HOST }}</h2> <h2>remote_address {{ scheme }}</h2> </body> </html>Copy the code

2. The HttpResponse object

  • Each attempt function must return a response object
attribute instructions
content string
charset A character encoding
status_code Status code
content_type Specifies the MIME type to output

The sample

    1. Don’t use the template
def hello(req):
    return HttpResponse("hello world")
def goodbye(req):
    res = HttpResponse()
    res.content = b'good bye'
    res.charset = "utf-8"
    res.content_type = 'text/html'
    return res
Copy the code
  • 2. Use a template
def studentlist(req):
    for key in req.GET.lists():
    print(key)
    allstudent = Student.objects.all()
    return render(req,'studentlist.html',context={'data':allstudent})
Copy the code
  • 3. Common methods
Write (content) Set content == obj.content set_cookie() Set cookie delete_cookie() Delete cookieCopy the code

3. JsonResponse object

  • JsonResponse is a subclass of HttpResponse and is used to return JSON data to the client. Typically used for Ajax requests. Its content-type defaults to application/json

  • class JsonResponse(data, encoder=DjangoJSONEncoder, safe=True,json_dumps_params=None, **kwargs)

Data: can be a dictionary, if safe set to False, can also be a json encoder serialized objects: encoding format, the default is django core. Serializers. Json. DjangoJSONEncoder safe: The default is True, and TypeError is reported if non-dictionaries are passed to dataCopy the code
  • The sample
HTTP import JsonResponse import json as myJson # def json(req): jsonStr = JsonResponse({'name':'zhangsan','age':18}) jsonStr = myJson.dumps({'name':'zhangsan','age':18}) return HttpResponse(jsonStr)Copy the code
  • Json.dumps returns data to Ajax. The JS code needs to parse the JSON data into JS objects using json.parse () and JsonResponse is automatically converted to JS objects (without the asynchronous json.parse () conversion).
def courselist(req): All () #QuerySet data = {' Course ':list(courses.values())} #QuerySet data = {' Course ':list(courses.values()) JsonResponse(data) # Pass dictionary to JsonResponseCopy the code
def courselist(req): Dumps (list(courses.values())) # query result set QuerySet = json string Serialize return JsonResponse(data,safe=False) #safe must be set to FalseCopy the code

redirect

  • Redirection without arguments
#urls.py urlpatterns = [ path('',views.index), re_path(r'^list/$',views.list_user), #views.py def redirect ($', views.redirect): return render(req,'index.html') def list_user(): return HttpResponse("list user") def Redirect(req): # return redirect('http://localhost:9000/') # return redirect('/') return redirect("list/")Copy the code
  • Redirection with parameters
#urls.py urlpatterns = [ path('repath/<int:num>/', views.repath), re_path(r'^parameter/(?P<num1>\d+)/(?P<num2>\d+)/$',views.parameter), ] #views.py def repath(req,num): Return redirect("parameter/3/5") def index(request): return HttpResponse(" home ") def parameter(req,num1, num2): return HttpResponse("num1={},num2={}".format(num1,num2))Copy the code
  • Reverse DNS
  • App_name specifies the namespace in urls.py and name= specifies the name in path
App_name = 'App' # namespace urlpatterns = [path(", views.index, Name ="index"), path('para/<int:num1>/<int:num2>/', "para"),] #res = reverse("App:index") # print(res,type(res)) #return redirect(res) # return redirect(reverse("App:para",args=(1,2))) # re_path Return redirect("App:para",kwargs={'num1':1,'num2':3}) < h2 > < a href = "/ form/" > show form < / a > < / h2 > < h2 > < a href ="/index/" > dead links without the cords jump < / a > < / h2 > < h2 > < a href = "/ args / 1/2 /" > dead links with the cords jump < / a > < / h2 > < h2 > < a href = "{% url 'App: index' %}" > dynamically generated routing address without the cords jump < / a > < / h2 > < h2 > < a href = "{% url 'App: args1' 2% 1}" > dynamically generated routing address with the cords jump < / a > </h2> </h2> <a href="{% url 'App:args1' num1=1 num2=2 %}">Copy the code

Default error view

  • Need to set DEBUG=False in Settings
  • Create an error attempt in the Templates directory
  • The sample