cookie and session django middleware

First, what is a cookie

1, since the BS architecture based on the HTTP protocol is stateless, can not save the client state

2, using the cookie / session technology can save the client user state

3, cookie is key to generate the server to the client on, the browser will save it

4, the browser can set the write prohibit cookie, that cookie is not saved

Two, django cookie operation

2.1 How to operate cookie

The view function returns an object is, just give the object to operate on it

# 一般有三种方式返回数据
obj = HttpResponse()
return obj

obj = render()
return obj

obj = redirect()
return obj

2.2 Operating cookie

1, generated cookie

# 生成cookie
obj.set_cookie('k1','v1',max_age=3)
obj.set_cookie('k1','v1',expires=3)
'''
1、客户端接收到的数据为键值对 k1:v1
2、参数max_age与expires都是设置cookies的有效时间,区别在于,当客户端为IE浏览器时,只能用expires
'''

2, the server get cookie

request.COOKIES.get('k1')  # 获取cookie值

3, delete the cookie

obj.delete_cookie('k1')

'''
删除cookie意味着注销客户端用户
定义注销视图函数即可'''
def logout(request):
    obj = redirect('/login/')
    obj.delete_cookie('user')

Third, what is the session

1, based on the data stored in the cookie client state on the server, usually stored in the database

2, cookie each client assigned a unique id

Four, django operation session

4.1 Creating cookie_session table

1, first create a list of items in django, when migrating to synchronize the database, it will default to create multiple tables, including table diango_sessioon

2, in the case of django_session table is created in order to manipulate the session

4.2 operating session

1, set the session

request.session['k1'] = 'v1'
'''
1、使用的k1:v1键值对,是生成cookie的相同的键值对
2、django内部自动调用算法生成一个随机的字符串
3、django_session表中添加数据
    以2中生成的字符串为主键session_key
    给数据加密生成字符串,添加进session表中session_data
    同时,自动生成session有效期限,mysql默认为14天  
'''

2, get session

request.session.get('k1')
'''
1、django内部会自动去请求头里面获取cookie
2、拿着session所对应的 随机字符串去django_session表中以一比对session_key
3、如果比对上了,获取对应的session_data,放入request.session中,以供程序员调用
4、如果没有比对上,那么request.session就是一个空字典
'''

3, delete session

request.session.delete()
'''
1、一个客户端对应django_session表中的一条数据
2、删除session,就是将该客户端对应的所有cookie删除
'''

4, sets the timeout

request.session.set_expiry(value)
'''
1、value是个整数,时间单位是秒
2、value是个datatime或者timedelta,那就是最后的有效期
3、value是0,用户关闭浏览器就会 失效
4、value是None,session会依赖全局session失效策略
'''

V. Example: login authentication

1, check cookie / session

2, the authentication fails, automatically jump page would have wanted to re-visit after visit

3, using CBV model

def login_auth(func):
    def inner(request, *args, **kwargs):
        next_url = request.get_full_path()
        print(next_url)
        print(request.session.get('username'))
        if request.session.get('username'):
            return func(request, *args, **kwargs)
        else:
            return redirect('/app01/login/%s/' % next_url)

    return inner


class MyLogin(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        user_obj = models.User.objects.filter(username=username, password=password)
        if not user_obj:
            return render(request, 'login.html')

        request.session['username'] = username

        url = reverse('home', kwargs={'username': username})
        obj = redirect(url)
        obj.set_cookie('username', username)
        return obj


class MyHome(View):
    @method_decorator(login_auth)
    def get(self, request, username):
        return render(request, 'home.html', {'username': username})
        pass

    def post(self, requeest, username):
        pass

Sixth, what is the middleware

  1. Middleware is a frame-level hooks for handling requests and responses Django, in essence, is a custom class
  2. Can be global to do some extra work before and after the implementation of the implementation of the internal view of the scope of functions, such as user login verification, user access frequency check, check user rights
  3. There are seven default in Django middleware
# settings.py文件
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',
]

Seven, custom middleware

  1. Middleware can define five methods
  2. Method Parameters request: required parameters, view and request functions as
  3. When the method returns a value of None, continues to proceed back according to the rules defined django
  4. When the return value HttpResponse object method, the object is returned directly to the user
# 在settings.py的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',
    'app01.mymiddleware.mymidd.MyMidd1',  # 自定义中间件MD1
    'app01.mymiddleware.mymidd.MyMidd2'  # 自定义中间件MD2
]

7.1 process_request

  1. The default method of process_request interior of each broker in order from top to bottom in the execution MIDDLEWARE
  2. Return HttpResponse object: The request will stop immediately backtrack from the current method of middleware process_response
# app01/mymiddleware/mymidd.py

from django.utils.deprecation import MiddlewareMixin

class MD1(MiddlewareMixin):
    def process_request(self, request):
        print("MD1里面的 process_request")


class MD2(MiddlewareMixin):
    def process_request(self, request):
        print("MD2里面的 process_request")
        pass

7.2 process_response

  1. After the view function, the default execution method of each process_response intermediate bottom in the order
  2. It must pass two parameters to the method, request and response
  3. Must return response: response is the HttpResponse object view function returns the browser to accept HttpResponse object
# app01/mymiddleware/mymidd.py

from django.utils.deprecation import MiddlewareMixin

class MD1(MiddlewareMixin):
    def process_request(self, request):
        print("MD1里面的 process_request")

    def process_response(self, request, response):
        print("MD1里面的 process_response")
        return response


class MD2(MiddlewareMixin):
    def process_request(self, request):
        print("MD2里面的 process_request")
        pass

    def process_response(self, request, response):
        print("MD2里面的 process_response")
        return response

7.3 process_view

  1. (After routing match) triggers before executing the view function
  2. Return HttpResponse object: in the middleware direct U-turn, a flashback to perform a process_response method, and finally returned to the browser
  3. The method takes four parameters
    1. request: HttpRequest objects
    2. view_func: Django view function object that will be used
    3. view_args: The positional parameters passed to the view list.
    4. view_kwargs is the keyword arguments passed to the dictionary of view (not including the request)
# app01/mymiddleware/mymidd.py
from django.utils.deprecation import MiddlewareMixin

class MD1(MiddlewareMixin):
    def process_request(self, request):
        print("MD1里面的 process_request")

    def process_response(self, request, response):
        print("MD1里面的 process_response")
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        print("-" * 80)
        print("MD1 中的process_view")
        print(view_func, view_func.__name__)


class MD2(MiddlewareMixin):
    def process_request(self, request):
        print("MD2里面的 process_request")
        pass

    def process_response(self, request, response):
        print("MD2里面的 process_response")
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        print("-" * 80)
        print("MD2 中的process_view")
        print(view_func, view_func.__name__)

7.4 process_exception

  1. View function automatically triggers an exception error, in accordance with the execution order from bottom to top
  2. Two request parameters and exception (Exception function abnormality generated Object View)
  3. Return HttpResponse object: Calling templates and process_response method middleware, and returned to the browser (no longer perform process_exception method)

7.5 process_template_response

  1. A rear view of the function execution is completed, the function returns the object has a view of the render () method are performed when, descending performed
  2. Two parameters request and response, which must return response

7.6 middleware implementation process

  1. Request arrives at the middleware, the middleware to execute each method according process_request positive sequence, after performing the matching route
  2. The method then sequentially performed process_view middleware, after the implementation of the function performed view
  3. If an exception view function, it will reverse execution process_exception
  4. If the object has a return function in view render () method will be performed in reverse order method process_exception
  5. Otherwise, reverse execution process_response method, the response to the client
  • The method has response parameters must return response (process_template_response, process_response)
  • None of the methods in response parameter (process_view, process_exception, process_response)
    1. Return none: normal execution
    2. The return HttpResponse: will eventually send the current response method middleware reverse order from the execution to the client

Above, process_request, process_view default order, process_exception, process_exception, process_response reverse defaults

Guess you like

Origin www.cnblogs.com/1012zlb/p/12005955.html