Django之cookie、session、token

cookie 与session

The purpose: to save the client state

The reason: Because the HTTP protocol is stateless

Because http protocol is stateless, so we need to invent technology can save the user

cookie:

A cookie is a key stored on the client browser's right, yes generated by the server, and then sent to the client browser to save. Therefore, the browser has written permission is prohibited cookie, you can set this function in the browser.

How django operation cookie:

    obj = HttpResponse()  # 利用obj对象才能操作cookie
    return obj

    obj = render()
    return obj

    boj = redirect()
    return obj 

Set cookie: obj.set_cookie ( 'k1', 'v1')

    obj.set_cookie('k1','v1')  # 告诉浏览器设置

获取cookie:request.COOKIES.get('k1')

request.COOKIES.get('k1')   # 获取浏览器携带过来的cookie值

Set timeout: obj.set_cookie ( 'k1', 'v1', max_age = 3)

obj.set_cookie('k1','v1',max_age=3)  # 针对谷歌浏览器,用max_age
obj.set_cookie('k1','v1',expires=3)  # 针对IE浏览器,用expires

Delete cookie (log out, Log out), generally will not be deleted.

Cookie-based user login achieve parity

装饰器
    用户在没有登录之前如果访问了一个需要登录之后才能访问的页面
    那么会先跳转到登录页面 用户输入用户名和密码并正确的情况下
    再自动跳转到之前用户想要访问的页面
        1.request.path_info
        2.利用get请求携带参数的方法

session:

session is stored on the server side above the key-value pairs

session working mechanism is the need to rely on the cookie

设置session:request.session['k1'] = 'v1'

request.session['k1'] = 'v1'
#  第一次设置的时候会报错,是因为你没有执行数据库迁移命令 生成django需要用到的一些默认表(django_session)
# django默认的session失效时间是14天  2周
request.session['k1'] = 'v1'

"""
执行上面这一句代码会发生了哪些事儿
1.djang内部自动帮你调用算法生成一个随机的字符串
2.在django_session表中添加数据(数据也是加密处理)
随机字符串         加密之后的数据           失效时间
ashdjsad            jsadsada
3.将产生的随机字符串返回给客户端浏览器 让浏览器保存
sessionid:随机字符串
"""

获取session:request.session.get('k1')

request.session.get('k1')
"""
1.django内部会自动去请求头里面获取cookie
2.拿着sessionid所对应的随机字符串去django_sessoion表中一一比对
3.如果比对上了 会将随机字符串对应的数据获取出来 自动放入request.session中供程序员调用
如果没有就是一个空字典
"""

删除session:request.session.delete()

request.session.delete()
# 客户端和服务端全部删除  只会根据浏览器的不同删对应的数据

Set expiration time: request.session.set_expiry (value)

# 设置会话Session和Cookie的超时时间
request.session.set_expiry(value)
    * 如果value是个整数,session会在些秒数后失效。
    * 如果value是个datatime或timedelta,session就会在这个时间后失效。
    * 如果value是0,用户关闭浏览器session就会失效。
    * 如果value是None,session会依赖全局session失效策略。

login session version check:

from functools import wraps


def check_login(func):
    @wraps(func)
    def inner(request, *args, **kwargs):
        next_url = request.get_full_path()
        if request.session.get("user"):
            return func(request, *args, **kwargs)
        else:
            return redirect("/login/?next={}".format(next_url))
    return inner


def login(request):
    if request.method == "POST":
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")

        if user == "alex" and pwd == "alex1234":
            # 设置session
            request.session["user"] = user
            # 获取跳到登陆页面之前的URL
            next_url = request.GET.get("next")
            # 如果有,就跳转回登陆之前的URL
            if next_url:
                return redirect(next_url)
            # 否则默认跳转到index页面
            else:
                return redirect("/index/")
    return render(request, "login.html")


@check_login
def logout(request):
    # 删除所有当前请求相关的session
    request.session.delete()
    return redirect("/login/")


@check_login
def index(request):
    current_user = request.session.get("user", None)
    return render(request, "index.html", {"user": current_user})

Session版登录验证

django session when data is created for the browser

As there can be several databases as follows:

Database software

file

RAM

token: encrypted string

The string processing algorithms using the encryption into ciphertext characters

django middleware

django middleware Introduction

Django settings.py file in the project file, there is a list of MIDDLEWARE middleware, by default there are seven:

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

As long as you want to do global functions of some sites you should consider using django middleware
1. Global user login verification
2 global user access frequency check
3. global user rights check () 20 lines of code 100+ RBAC

It is said: In all framework, django middleware is the most perfect

Custom Method 5

django middleware supports user-defined, gives five methods can be customized:

1、process_request

When the request method will follow process_request sequentially performed in order from top to bottom of each profile settings defined within the middleware, the middleware is not the method if the internal skip execution of the next intermediate.

Once any middleware return HttpResponse object, name request will be immediately halted, and then backtrack

2、process_response

2.1 Response time will go process_response method profile settings defined within each broker in accordance with the order from the bottom, in sequence.
2.2 The method must have two parameters, and must return response parameter, it will not return an error
2.3 The method returns nothing (HttpResponsed object) the front end of what is obtained

Note: When process_request method returns an HttpResponse object will go back directly from inside process_respone current middleware, middleware is not executed will no longer perform

3、process_view(self, request, view_name, *args, **kwargs)

Before performing the trigger function view after successfully matched routing 3.1
3.2 If the method will then return to the HttpResponse object from the bottom up through each broker once inside process_response method

4、process_template_respose

1. When you return objects contained render attribute points to a render method will trigger upward from the lower order

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

5、process_exception

View function when an error occurs, it will automatically trigger the order is from the bottom up. hair

CRM customer relationship management system

Customer Relationship Managment

Guess you like

Origin www.cnblogs.com/allenchen168/p/11991118.html