django-cookie

Cookie---客戶端瀏覽器存儲的一組鍵值對{key:value}javascript

 

在django中cookie的用法:html

1.cookie值獲取:java

request.COOKIE是一個字典
request.COOKIE['name']
request.COOKIE.get('name')

for k,v in request.COOKIE.items():
    print(k,v)

print(request.COOKIE.keys())
print(request.COOKIE.values())

2.在服務器端,操做cookie方法:django

name = request.POST.get("name")
res = render(request,」login.html「)
res = redirect(」/login「)
#設置cookie
res.set_cookie("name",name)#設置cookie
res.set_cookie("name",name,max_age=10)#設置cookie超時時間
res.set_signed_cookie(key,value,salt="dandnao")#加鹽操做
return res

#獲取cookie
v = request.get_signed_cookie(key,salt="dandnao")#獲取cookie
注意:使用上述方法時,若是沒有設置默認值,當獲取不到cookie時,系統會出異常,爲了解決此問題,咱們能夠設置默認值,defautl=None,無此cookie返回none


cookie參數:
    max_age = none,設置超時時間,時間單位爲s
    expires = none,設置超時日期
    example:
        import time
        current_time = datetime.datetime.utctime()
        current_time = current_time+datetime.timedelta(second=5)

        expires = current_time

    path:'/'#cookie生效路徑,'/'表示任何url均可以訪問
    domain =none #cookie生效域名
    secure =False,https傳輸
    httponly = False,只能http傳輸,沒法被javascript抓取

3.cookie保存於客戶端,因此經過客戶端也能夠對cookie進行操做瀏覽器

  1. javascript
  2. jQuery

  1.javascript操做服務器

  document.cookiecookie

  略.....百度網絡

  2.jQuery操做dom

因爲客戶端操做cookie方式較爲繁瑣,咱們能夠下載網絡上提供用於操做cookie的插件:jQueryCookie
<script src="/static/js/jQuery.cookie.js>
    $.cookie("list_per_num,30,{path:'/'});
</script>

4.cookie之裝飾器ide

    裝飾器解釋:
    def auth(func):
        def inner(request,*args,**kwargs):
            start=datetime.time()
            return func(request,*args,**kwargs)
            end = datetime.time()-start
            print('函數執行時間',end)
        return inner
裝飾器源碼

  調用方式1

        @auth == 》index=auth(index)
    返回的是index的內存地址,參數能夠放置在第二層以後。。。。。


    裝置器之FBV:
        @auth
        def index(request):
        ..........    
裝飾器之FBV

  調用方式2

#須要導如jango爲咱們提供的裝飾模塊
    from django.utils.decorators import method_decorator
    from jango import views

    @method_decorator(auth,'dispatch')
    class index(views.View):
        @method_decorator(auth)
        def dispatch(self, request, *args, **kwargs):
                    result = super(inidnao, self).dispatch(request, *args, **kwargs)
                    return result    
    
        @method_decorator(auth)
        def get(self,request):
        .......
        def post(self,request)

#注意:class 須要再urls中,views.index.as_views()
裝飾器之CBV
相關文章
相關標籤/搜索