60 django- cookie and session and middleware

A, cookie and session

1. Why have these technologies

cookie and session appeared to save the user the status of the client.

In essence, in fact, because the HTTP protocol is stateless, no way to save the customer's login information and status, and therefore need to use the session cookie to store the user's status.

cookie

A cookie is a container for the client to record user information, it is stored in the form of key-value pairs, for example {'username':'st'}.

When the cookie is sent to the server, the server can identify the user's identity information carried in the cookie. Can know in the end is Joe Smith or John Doe in the access server access server.

This leads to certain functions when used by users, you must be logged in to let the server know to use the user's identity. For example, Taobao's shopping cart, everyone is different, you just landed, in order to access your shopping cart.

This leads users to sign in each time you visit, it is very troublesome. If you can log in once to record the state, it is very convenient.

cookie came into being.

After the user logs in, the login information is stored in a browser cookie, simply log in to enter information once, next time visit, the browser will automatically help you send a cookie.

The server that the user information, you do not have to manually enter many times, all is well, flattered!

session

Everything is not absolute.

User information in the cookie records often contain some private information. For example, sensitive information such as passwords.

When the cookie stored in your browser, the cookie information will be subject to various risk of accidental leakage.

Once the leak is likely to lead to disaster.

To solve this problem, session turned out.

When the user enters login information, user information is passed back-end server, the server will be encrypted and the data stored in the server, and then give this information labeled a "session_id" label named. This "session_id" is really just a randomly generated string used to mark this user information, easy to find.

Through this "session_id", the server can quickly access to this user information.

So what use is it?

So the browser will not store user information up. The server can be "session_id" returned to the browser, the browser will "session_id" cookie value as key-value pairs are saved.

In this way, the next time the user wants to access, the browser will include "session_id" the cookie to the server, the server first user information stored on the server before landing found by "session_id", the server can know the user identity mess!

So far successful landing! Users no longer have to frequently enter information, not afraid of information leaking mess!

Of course, session is not perfect, but only when compared to the safety performance has been greatly improved cookie, which was widely advertised, programmers have to follow. . .

Although the cookie can be stored on the client browser, but because it is set out by the server, the browser cookie is entitled to prohibit writing.

How to set a cookie 2.1 Django

We need to be provided with cookie base class instance of three views of the object obj.

obj = HttpResponse()
# 利用obj对象你才可以操作cookie
# obj = render()
# obj = redirect()

obj.set_cookie('k1','v1')
# 设置用盐加密的cookie
obj.set_signed_cookie(key,value,salt='加密盐',)

def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'st' and password == '123':
            # 如果登录信息完整,就返回主页
            obj = redirect('/home/')
            
           # 告诉浏览器,保存这一对cookie
            obj.set_cookie('username','st')
            
            return obj
    return render(request,'login.html')

2.2 Django how to get cookie

def home(request):
    if request.COOKIES.get('username'):
        print(request.COOKIES.get('username'))
        # st
        return HttpResponse('只有登录的人才能看到')
    return redirect('/login/')

2.3 Django how to set a cookie timeout

In set_cookiesuse max_age, expires parameter

obj.set_cookie('k1','v1',max_age=3)
obj.set_cookie('k1','v1',expires=3)
# 两个参数都是设置超时时间  并且都是以秒为单位
# 区别:expires可以给IE浏览器设置cookie的超时时间

def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'st' and password == '123':
            obj = redirect('/home/')
            obj.set_cookie('username','st',expires=3)
            # 告诉浏览器,保存这一对cookie
            # expires=3单位为秒,max_age一样
            return obj
    return render(request,'login.html')

2.4 Django how to jump to the page you want to access through the cookie

Login authentication can be done in decorator

# 用来跳回用户登录前想访问的页面的装饰器
from functools import wraps
def login_auth(func):
    @wraps(func)
    def inner(*args,**kwargs):
        # 判断当前用户是否登录
        request = args[0]
        # print(request)
        # print(request.GET)
        # print(request.path_info)  # 只获取url,不获取get参数
        # print(request.get_full_path())  # # url+get参数
        if request.COOKIES.get('username'):
            res = func(*args, **kwargs)
            return res
        else:
            # 获取到用户想要访问的页面的url
            path = request.path_info
            # 将该url当做get参数传入login函数
            return redirect(f'/login/?path={path}')
    return inner


# login
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'st' and password == '123':
            # 获取get参数,取得用户想要访问的url
            path = request.GET.get('path')
            if path:
                obj = redirect(path)
            else:
                # 如果path没值,可能用户是直接访问的login视图,因此登录后默认返回到home首页
                obj = redirect('/home/')

            obj.set_cookie('username','st')
            return obj
    return render(request,'login.html')

How to delete cookie 2.5 Django

By delete_cookiedeleting the cookie function.

def logout(request):
    obj = redirect('/logout/')
    obj.delete_cookie('username')
    return obj

3. session

session is stored on the server-side pairs.

session working mechanism is the need to rely on the cookie.

3.1 Django setting session

The default expiration time of two weeks, 14 days

def set_session(request):
    request.session['k1'] = 'ok123'
    return HttpResponse('session已设置')

What happened in the end internal Django:

  1. The acquired data is added in the form of key-value pairs to a big dictionary, the dictionary will be stored encrypted.
  2. Automatically generating a random string, as session_id encrypted data obtained in the previous step. In key-value pairs { 'session_id':} form of encrypted data stored in the reservoir. Corresponding to the encrypted data may be acquired by session_id.
  3. Session_id will return to the front-end browser. So the next to carry browser cookie to access, back-end server can get the cookie session_id, so that you can gain access to encrypted data stored in the reservoir by session_id. Then 'encryption algorithm used when encrypting the encrypted data' corresponding decryption algorithm to decrypt the encrypted data, the key can be acquired in the form of stored data.
  4. The next time the same browser needs to store a set of private data while, Django automatically decrypted Dictionary of the corresponding browser, a new key-value pair is added to this large dictionary, re-encrypted, stored, instead of the previous Dictionary of encryption, so that a browser will be the only piece of data.

3.2 Django acquisition session

# 获取session
def get_session(request):
    res = request.session.get('k1')
    print(res)
    return HttpResponse('获取成功')

What happened in the end internal Django:

  1. Django server to obtain from the front office to the browser cookie
  2. Fetches the corresponding 'session_id' values ​​from the cookie
  3. Dictionary of obtaining the encrypted value corresponds to the database by session_id
  4. The Dictionary of encryption and decryption, to obtain a large dictionary
  5. request.session = big dictionary
  6. Request.session can then by '.get' way values ​​from the dictionary.
res = dict(request.session)
print(res)

# 强制类型转换一下,发现确实是一个字典
# {'k1': 'ok123', 'k2': 'ok321'}

3.3 Django delete session

# 删除session
def del_session(request):
    
    # 删除当前会话的所有Session数据
    # request.session.delete()
    
    # 删除当前的会话数据并删除会话的Cookie,
    # 用于确保前面的会话数据不可以再次被用户的浏览器访问.建议使用
    request.session.flush()
    return HttpResponse('shanle ')

3.4 Django set session expiration time

# request.session.set_expiry(value)
request.session.set_expiry(5)  # 单位为秒

When a strip session fails, the data valid will be screened from a large dictionary out as a separate data table on the session, it is not immediately clear, but the presence of the first session list, each over a period of time , django will enable automatic cleanup, the failure of the session time has elapsed deleted.

3.5 Django setting memory for storing the session

1. 数据库Session
SESSION_ENGINE = 'django.contrib.sessions.backends.db'   # 引擎(默认)

2. 缓存Session
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'  # 引擎
SESSION_CACHE_ALIAS = 'default'                            # 使用的缓存别名(默认内存缓存,也可以是memcache),此处别名依赖缓存的设置

3. 文件Session
SESSION_ENGINE = 'django.contrib.sessions.backends.file'    # 引擎
SESSION_FILE_PATH = None                                    # 缓存文件路径,如果为None,则使用tempfile模块获取一个临时地址tempfile.gettempdir() 

4. 缓存+数据库
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'        # 引擎

5. 加密Cookie Session
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'   # 引擎

其他公用设置项:
SESSION_COOKIE_NAME = "sessionid"                       # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串(默认)
SESSION_COOKIE_PATH = "/"                               # Session的cookie保存的路径(默认)
SESSION_COOKIE_DOMAIN = None                             # Session的cookie保存的域名(默认)
SESSION_COOKIE_SECURE = False                            # 是否Https传输cookie(默认)
SESSION_COOKIE_HTTPONLY = True                           # 是否Session的cookie只支持http传输(默认)
SESSION_COOKIE_AGE = 1209600                             # Session的cookie失效日期(2周)(默认)
SESSION_EXPIRE_AT_BROWSER_CLOSE = False                  # 是否关闭浏览器使得Session过期(默认)
SESSION_SAVE_EVERY_REQUEST = False                       # 是否每次请求都保存Session,默认修改之后才保存(默认)

Django中Session相关设置

Two, Django middleware

1. Default Middleware

If you want to do some of the site's overall functionality, you should give priority to use django middleware.

E.g:

1. Global user login verification
2. The overall frequency of user access verification
3. The global user rights check ()

django middleware framework which is all to do the most perfect.

# settings
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',
]

These are the seven default django middleware.

The nature of middleware is actually one of the class, the class of the following methods will be triggered automatically at specific stages:

1.process_request

2.process_response

3.process_view

4.process_template_response

5.process_exception

2. Custom Middleware

Custom middleware need to create a py file name can easily take, and then import that file MiddlewareMixinmodule generates subclasses.

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse,render,redirect
# 接下来可以定义类,继承MiddlewareMixin模块,该类就成为了一个中间件

class MyMdd1(MiddlewareMixin):
    def process_request(self,request):
        pass
    
# 。。。。。。

2.1. Need to know

  1. process_request

    1. When the request will be from top to bottom, are sequentially performed for each intermediate process_request method according to internal settings defined in the configuration file.

    2. If no internal intermediate method, skip execution of the next intermediate.

    3. The method Once the return HttpResponse object, then the request will immediately stop go back immediately backtrack.

    We will go back directly from the inside of intermediate 4. After the current process_respone process_request method returns HttpResponse object. Backtrack. Middleware is not executed will no longer perform.

def process_request(self,request):
    print('我是第一个中间件里面的process_request方法')
    # return HttpResponse("我是中间件一里面的")
  1. process_response

    1. The response will take the time settings according to the configuration file in the order from the bottom, the method sequentially executed process_response defined within each broker.

    2. The method must have two parameters, parameter and must return response is not returned directly given.

    3. The method returns nothing (HttpResponsed object) the front end of what can be obtained.

def process_response(self,request,response):
    """
    :param request:
    :param response: 就是后端返回给前端的数据
    :return:
    """
    print('我是第一个中间件里面的process_response方法')
    return response

2.2 Understanding

  1. process_view

    Trigger before executing the view function 1. After routing a successful match.

    2. If the method returns an HttpResponse object, will be up again after each broker from inside process_response method.

def process_view(self,request,view_name,*args,**kwargs):
    print(view_name)  # 函数内存地址
    print(args)
    print(kwargs)
    print('我是第一个中间件里面的process_view方法')
  1. process_template_response

    1. The view function is executed after execution is completed immediately, but there is a precondition that the object function returns view must have a render () method (or indicating that the target object is a TemplateResponse or equivalent method). Or will not trigger.

def process_template_response(self, request, response):
    print('我是第一个中间件里面的奇葩方法')
    return response


# views
def mdzz(request):
    print('我是视图函数mdzz')
    def render():
        return HttpResponse('你好呀 我是奇葩')
    obj = HttpResponse('我很好 好的像个傻逼一样')
    obj.render = render
    return obj
  1. process_exception

    1. triggered automatically when an error occurs view function, the order is from bottom to top

def process_exception(self,request,exception):
    print('我是第一个中间件里面的process_exception')
    print(exception)

Guess you like

Origin www.cnblogs.com/bowendown/p/11986507.html