Session cookie and held state and the process outlined view class middleware description

Copyright: Changan white https://blog.csdn.net/weixin_44074810/article/details/91045507

State holding

  1. The browser requests the server is stateless
  2. Stateless: when referring to a user request, the browser, the server can not know what the user has done before, is a new request every request.
  3. Stateless reasons: browser and the server is using Socket socket communication, the server will request the results after the return to the browser, it will close the current Socket connection, and the server will be destroyed after processing the page object page is completed.
  4. Sometimes the need to keep down the state of the user's browser, such as whether the user is logged in,
  5. Browse through which commodities
  6. Implement state remains mainly in two ways:
    ① use information stored in the client Cookie
    ② use the server to store information Session

1. The data stored in the client is called: the cookie
the cookie is name-based (IP) -based

Will have to change when replacing the client, and the domain name (IP)

The first request procedure
① not carry any browser cookie information server first requests
② After the server receives the request, the request is not issued cookie information
③ setting a server cookie, the cookie is set in the response
④ the browser receives a response and found that the response has cookie information, this will save up cookie information
a second time and after the process of
requesting anything after the second and ⑤ browser to carry this cookie information
⑥ after this time the server receives a request'll find request carried cookie information, then you know this is requested

expire date

max_age: is representative of number of seconds None default
time is received from the server request time after time + number of seconds
max_age =

Delete the cookie
first way: delete
response.delete_cookie (key)
The second way to make = 0 max_age
response.set_cookie (Key, value, max_age = 0)

2. The data stored in the server-side call: session

session need to rely on the cookie
request.session is a dictionary
if the browser to disable the cookie, the session can not be achieved

The first request
① client sends a post request with the user name and password to the server, Cookie are no
② After the server receives the request, authenticate the user name and password, verify that no problem may be disposed session information
③ setting session information at the same time, the server will automatically set a cookie information in the response header sessionid
④ after the client end receives a response, it will save the cookie information (information sessionid) is
requested after the second and
after the second and ⑤ will request carries session id information
⑥ when the server receives this request, the information will take the sessionid, then verification, validation is successful, then the information can be acquired session (session information stored in the server)

session is the client data from the saved
session is contained in the cookie of
the second request and will later include cookie information, cookie information, there is a session
cookie information in the request header

When setting session session to do two things
1. The data stored in the database
2. Set a cookie information, this information is sessionid cookie is key

Class View and middleware

Class object-oriented view is used in the idea

Django class may also be used to define a view, view class is called.

  1. Defined class view
    ① inherited from View (from django.views import View)
    different ways ② requests have different business logic
    class view of the direct method using the http request method name as our function names such as: get, post, put
    the second parameter method ③ view class instance object must be a request
    for class view must have a return value is returned and its subclasses HttpResopnse

from django.views.generic import View

RegisterView class (View):
"" "class view: processing registration" ""

def get(self, request):
    """处理GET请求,返回注册页面"""
    return render(request, 'register.html')

def post(self, request):
    """处理POST请求,实现注册逻辑"""
    return HttpResponse('这里实现注册逻辑')

Class view of the benefits
1. good readability
2. Class view relative to the view function has a higher reusability, if the rest need to use a particular logical view of a class, you can view the direct successor to the class

Defining classes need to inherit parent view from View Django provided,
may be used from django.views.generic import View
or imported from django.views.generic.base import View

When configuring the route, using the class view as_view () method to add.

= the urlpatterns [
# view function: Register
# URL (R & lt '^ Register / Katex the parse error: the Expected' the EOF ', GOT' # 'AT position 42 is: ... egister'), # class view: ... registered URL ', views. RegisterView.as_view (), name = 'Register'),
]

Class View principles

@classonlymethod
def as_view(cls, **initkwargs):
“”"
Main entry point for a request-response process.
“”"
…省略代码…

    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        # 调用dispatch方法,按照不同请求方式调用不同请求方法
        return self.dispatch(request, *args, **kwargs)

    ...省略代码...

    # 返回真正的函数视图
    return view


def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

Multiple inheritance override the dispatch class view

class CenterView(View):

def get(self,request):
    return HttpResponse("OK")

def post(self,request):
    return HttpResponse("OK")

Multiple inheritance using object-oriented features.

class CenterView(LoginRequireMixin,View):

def get(self,request):
    return HttpResponse("OK")

def post(self,request):
    return HttpResponse("OK")

Middleware

Django middleware in a lightweight, underlying plug-in system, can intervene Django request and response process, modifying the input or output Django.
Middleware is designed to provide a non-intrusive way for developers to develop and enhance the robustness of the Django framework.
We can use middleware to intervene input or output at different stages of processing Django view.

1 middleware definition method
① define a plant middleware function, and then returns a middleware can be invoked.
② middleware factory function needs to receive a get_response objects can be invoked.
③ Back middleware also can be called a target, and the same as the view needs to receive a request object and returns a response object.

: def simple_middleware (get_response)
perform a code written # here only for the first time in the Django configuration and initialization time.

def middleware(request):
    # 此处编写的代码会在每个请求处理视图前被调用。

    response = get_response(request)

    # 此处编写的代码会在每个请求处理视图之后被调用。

    return response

return middleware

For example, create a new file in the book middleware.py applications,

def my_middleware(get_response):
print(‘init 被调用’)
def middleware(request):
print(‘before request 被调用’)
response = get_response(request)
print(‘after response 被调用’)
return response
return middleware

After the definition of a good middleware needs in settings.py add middleware registration file

MIDDLEWARE = [
‘django.middleware.security.SecurityMiddleware’,
‘django.contrib.sessions.middleware.SessionMiddleware’,
‘django.middleware.common.CommonMiddleware’,
# ‘django.middleware.csrf.CsrfViewMiddleware’,
‘django.contrib.auth.middleware.AuthenticationMiddleware’,
‘django.contrib.messages.middleware.MessageMiddleware’,
‘django.middleware.clickjacking.XFrameOptionsMiddleware’,
‘book.middleware.my_middleware’, # 添加中间件
]

Define a view for testing

Middleware DEF (Request):
Print ( 'View view is called')
return the HttpResponse ( 'the OK')

The results of
init is called
before request is called
view view is called
after reponse is called

Note: Django running in debug mode, middleware init some of them might be called twice.

The execution order of the plurality of intermediate 2

1. 在请求视图被处理前,中间件由上至下依次执行
2. 在请求视图被处理后,中间件由下至上依次执行

Example:

Define two middleware

def my_middleware(get_response):
print(‘init 被调用’)
def middleware(request):
print(‘before request 被调用’)
response = get_response(request)
print(‘after response 被调用’)
return response
return middleware

def my_middleware2(get_response):
print(‘init2 被调用’)
def middleware(request):
print(‘before request 2 被调用’)
response = get_response(request)
print(‘after response 2 被调用’)
return response
return middleware

Register to add two middleware

MIDDLEWARE = [
‘django.middleware.security.SecurityMiddleware’,
‘django.contrib.sessions.middleware.SessionMiddleware’,
‘django.middleware.common.CommonMiddleware’,
# ‘django.middleware.csrf.CsrfViewMiddleware’,
‘django.contrib.auth.middleware.AuthenticationMiddleware’,
‘django.contrib.messages.middleware.MessageMiddleware’,
‘django.middleware.clickjacking.XFrameOptionsMiddleware’,
‘users.middleware.my_middleware’, # 添加
‘users.middleware.my_middleware2’, # 添加
]

Results of the

init2 is called
init is called
before request is called
before request 2 is called
view view is invoked
after response 2 is invoked
after response is called

Guess you like

Origin blog.csdn.net/weixin_44074810/article/details/91045507