Python自动化之模板继承和cookie

request请求头信息

type(request) //查看类
from django.core.handlers.wsgi import WSGIRequest

结果会以字典的形式存在

request.environ封装了用户所有请求信息

模板继承

主模板

{% block content %}
{<% endblock %}

字模板
开头导入

{% extends "master.html" %}

{% block content %}

内容

{% endblock %}

导入其他标签

{% include "master.html" %}

主模板可以渲染

simple_tag

  1. 在app下新建一个templatetags目录,建一个py文件.
  2. from django import template
    from django.utils.safestring import mark_safe
    register = template.Library()
    @register.simple_tag
  3. 在主模板添加{% load py文件名%}称 ,{% 函数名称 %}}

例1:没有参数

tianqi.py
--------------
def number():
	return 123

主模板	
{% load tianqi %}
{% number %}

例2:有参数

tianqi.py
--------------
def number(a1,a2):
	return 123

主模板	
{% load tianqi %}
{% number a1 a2 %}

可以加很多参数,不可以加到if语句里,例如{% if number a1 a2 %}是不允许的
例2:有参数

@register.filter
def number1(a1,a2):
	return 123

{{ "123"|number1:"456" }}

最多支持2个参数,但是支持

cookie是客户端的一个小文件
应用场景:用户登录认证

def login(request):
    if request.method == "GET":
        return render(request,'login.html')
    if request.method == "POST":
        u = request.POST.get('username')
        p = request.POST.get('pwd')
        dic = user_info.get(u)
        if not dic:
            return render(request,'login.html')
        if dic['pwd'] == p:
            res = redirect('/index/')
            # res.set_cookie('username111',u,max_age=10)
            # import datetime
            # current_date = datetime.datetime.utcnow()
            # current_date = current_date + datetime.timedelta(seconds=5)
            # res.set_cookie('username111',u,expires=current_date)
            res.set_cookie('username111',u)
            res.set_cookie('user_type',"asdfjalskdjf",httponly=True)
            return res
        else:
            return render(request,'login.html')

def index(reqeust):
# 获取当前已经登录的用户
    v = reqeust.COOKIES.get('username111')
    return render(reqeust,'index.html',{'current_user': v})

res.set_cookie('username111',u)设置cookie
v = reqeust.COOKIES.get('username111')获取cookie
关闭浏览器cookie失效


参数:
        key,              键
        value='',         值
        max_age=None,     超时时间
        expires=None,     超时时间(IE requires expires, so set it if hasn't been already.)
        path='/',         Cookie生效的路径,/ 表示根路径,特殊的:跟路径的cookie可以被任何url的页面访问
        domain=None,      Cookie生效的域名
        secure=False,     https传输
        httponly=False    只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖)

加密cookie

obj.set_signed_cookie('username',"kangbazi",salt="asdfasdf")
request.get_signed_cookie('username',salt="asdfasdf")        

jquery cookies

var v = $.cookie('per_page_count', {'path': "/user_list/`"});

FBV装饰器

	- 装饰器
		FBV:
			def auth(func):
				def inner(reqeust,*args,**kwargs):
					v = reqeust.COOKIES.get('username111')
					if not v:
						return redirect('/login/')
					return func(reqeust, *args,**kwargs)
				return inner

CBV装饰器

CBV:
from django import views
from django.utils.decorators import method_decorator

			@method_decorator(auth,name='dispatch')
			class Order(views.View):

				# @method_decorator(auth)
				# def dispatch(self, request, *args, **kwargs):
				#     return super(Order,self).dispatch(request, *args, **kwargs)

				# @method_decorator(auth)
				def get(self,reqeust):
					v = reqeust.COOKIES.get('username111')
					return render(reqeust,'index.html',{'current_user': v})

				def post(self,reqeust):
					v = reqeust.COOKIES.get('username111')
					return render(reqeust,'index.html',{'current_user': v})					

第一种写法

			from django import views
			from django.utils.decorators import method_decorator

			class Order(views.View):

				@method_decorator(auth)
				def get(self,reqeust):
					v = reqeust.COOKIES.get('username111')
					return render(reqeust,'index.html',{'current_user': v})
				@method_decorator(auth)	
				def post(self,reqeust):
					v = reqeust.COOKIES.get('username111')
					return render(reqeust,'index.html',{'current_user': v})

第二种写法

			from django import views
			from django.utils.decorators import method_decorator
			class Order(views.View):

				@method_decorator(auth)
				def dispatch(self, request, *args, **kwargs):
				    return super(Order,self).dispatch(request, *args, **kwargs)

				def get(self,reqeust):
					v = reqeust.COOKIES.get('username111')
					return render(reqeust,'index.html',{'current_user': v})

				def post(self,reqeust):
					v = reqeust.COOKIES.get('username111')
					return render(reqeust,'index.html',{'current_user': v})

第三种写法(最简单 推荐)

			from django import views
			from django.utils.decorators import method_decorator

			@method_decorator(auth,name='dispatch')
			class Order(views.View):

				def get(self,reqeust):
					v = reqeust.COOKIES.get('username111')
					return render(reqeust,'index.html',{'current_user': v})

				def post(self,reqeust):
					v = reqeust.COOKIES.get('username111')
					return render(reqeust,'index.html',{'current_user': v})
posted @ 2017-01-02 22:57  Dus  阅读(270)  评论(0编辑  收藏  举报