day58 cookie session middleware

cookie and session introduction and operation

Why have these technologies
1. The purpose is to save the user the status of the client
2 reasons: HTTP protocol is stateless

cookie: save the key on the client browser for
the key While cookie is stored on the client browser's right, but it is set by the server, the browser cookie prohibition of the right to write

How django cookie operations

White will be three tricks
using the object obj can operate cookie

obj=HttpResponse()
obj=render()
obj=redirect()
return obj

Set cookie

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

Get cookie

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

Set cookie timeout

Both parameters are set time, and are in seconds
difference: If you want to set IE browser cookie timeout, only use expires

obj.set_cookie('k1','v1',max_age=3)
obj.set_cookie('k1','v1',expires=3)

Delete cookie

(注销  退出登录)
obj.delete_cookie('k1')
def login(request):
    if request.method=='POST':
        username=request.POST.get('username')
        password=request.POST.get('password')
        if username=='jason' and password=='123':
            old_path=request.GET.get('next')
            if old_path:#防止用户直接访问login页面
                obj=redirect(old_path)
            else:
                obj=redirect('/home/')#默认跳转到首页
            # obj.set_cookie('whoami','jason',max_age=10)#告诉浏览器保存一个键值对,max_age=10:十秒后失效
            obj.set_cookie('whoami','jason')#告诉浏览器保存一个键值对,max_age=10:十秒后失效
            return obj
    return render(request,'login.html')

#装饰器
from functools import wraps
def login_auth(func):
    @wraps(func)
    def inner(request,*args,**kwargs):
        #判断当前用户是否登录
        print(request.path_info)#只获取url
        print(request.get_full_path())#获取url+get参数
        if request.COOKIES.get('whoami'):
            res=func(request,*args,**kwargs)
            return res
        else:
            target_path=request.path_info
            return redirect('/login/?next=%s'%target_path)
    return inner

@login_auth
def home(request):
    #校验用户是否登录
    # if request.COOKIES.get('whoami'):
    return HttpResponse('home页面 只有登录的人才可以访问')

@login_auth
def index(request):
    return HttpResponse('index页面 只有登录的人才可以访问')

@login_auth
def logout(request):
    obj=redirect('/login/')
    obj.delete_cookie('whoami')
    return obj

session

session: key stored on the server side of the
working mechanism session is dependent on the cookie

Set session

django session when data is created, it is for the browser

request.session['k1']='v1'

The first time setting will complain: no command to perform a database migration, generate some django need to use the default table (django_session)

The default session django expiration time is 14 days

request.session [ 'k1'] = ' v1' doing those things:
1.django internal call algorithm automatically generates a random character string (the data is encrypted)
2. Add django_session data in
the data encrypted random string after failure time
dnsfj ksdfjksjfksjfdjf
randomly generated string 3. returned to the client browser, so the browser stores
sessionid: random string

Obtaining session

request.session.get('k1')

1.django internal to automatically obtain the cookie request header which
random string holding sessionid 2. django_session corresponding to eleven alignment table
3. The ratio of the corresponding random string will be out of data acquisition on automatically on request.session CCP programmer calls. If that is not an empty dictionary on comparison

Delete session

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

Set session expiration time

request.session.set_expriy(5)
request.session.set_expriy(value)
如果value是一个整数,session会在value秒数之后失效
如果value是一个datatime或timedelta,session就会在这个时间后失效
如果value是0,用户关闭浏览器session就会失效
如果value是None,session会依赖全局session失效策略
def set_session(request):#设置session
    request.session['k1']='jason666'
    request.session.set_expiry(10)#设置失效时间
    # request.session['k2']='json666'
    # request.session['k']='jasn666'
    return HttpResponse('设置成功')

def get_session(request):#获取session
    if request.session.get('k1'):
        # res=request.session.get('k1')
        # res=request.session.get('k2')
        # res=request.session.get('k3')
        return HttpResponse('获取成功')
    return HttpResponse('失效了')

def delete_session(request):#删除session
    request.session.delete()#客户端 服务端全部删除
    # request.sesion.flush()#建议使用这个
    return HttpResponse('删除了')

supplementary session

It can be used as a database: database software (relational, non-relational), file, memory

token: encrypted string

django middleware

There are seven default django middleware:

As long as you want to do some of the site's overall functionality, you should consider using django middleware
1. Global user login verification
2 global user access frequency check
3. global user rights check
django middleware so the framework is there to do the most perfect

Target character string "" "" reflecting
global "" "" "" "" middleware

seven default django middleware, middleware and supports user-defined, and then exposed to five user can customize the method of

You need to know:

process_request

1. When the request will be from top to bottom, are sequentially performed for each intermediate internal process_request method defined according to the profile settings, if the method is not inside the middleware, the middleware perform the next skip
2. The method Once the return HttpResponse object, then the request will immediately stop next to go, immediately backtrack

process_response

1. The response time will go from bottom to top order, are sequentially performed for each intermediate process_response method defined according to internal settings profiles.
2. The method must have two parameters, and must return response parameter, an error does not return directly to
3. The method returns nothing (httpResponsed object), the front end will be able to gain any

When httpResponsed process_request method returns an object, it will go back directly from inside process_response current middleware, middleware is not executed will no longer perform

You need to know:

process_view

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

Trigger before executing the view function 1. After successfully matched routing
2. If the method returns an HttpResponse object, will be from the bottom up through the inside of each broker method process_response

process_template_response

1. When you return the object contains a render attribute points to render method will trigger, bottom-up order

process_exception

1. When an error occurs in view of the function, automatically triggers the order is from bottom to top

Above five methods, automatically triggers a particular stage (if the parameter contains a response, it must be returned)

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse,redirect,render
class MyMdd1(MiddlewareMixin):
    def process_request(self,request):
        print('我是第一个中间件里面的process_request方法')
        # return  HttpResponse('我是中间件一里面的')

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

    def process_view(self,request,view_name,*args,**kwargs):
        # print(view_name)
        # print(args)
        # print(kwargs)
        print('我是第一个中间件里面的process_view方法')
        # return HttpResponse('我是中间件一里面的process_view')

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

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

class MyMdd2(MiddlewareMixin):
    def process_request(self,request):
        print('我是第二个中间件里面的process_request方法')
        # return HttpResponse('我是中间件二里面的')

    def process_response(self,request,response):
        print('我是第二个中间件里面的process_response方法')
        return response
        # return HttpResponse('我是中间件二里面的')

    def process_view(self,request,view_name,*args,**kwargs):
        # print(view_name)
        # print(args)
        # print(kwargs)
        print('我是第二个中间件里面的process_view方法')
        # return HttpResponse('我是中间件二里面的process_view')

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

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

How do rights management middleware

Guess you like

Origin www.cnblogs.com/zqfzqf/p/11986379.html