标签:begin ted token decorator lis auto 方式 不可 函数
notify.email
的from···import类型# importlib模块(以导入json模块为例)
import importlib
json = importlib.import_module('json')
module = importlib.import_module('notify.email')
# settings.py
NOTIFY_LIST = [
'notify.email.Email',
'notify.msg.Msg',
'notify.wechat.WeChat',
'notify.qq.Qq',
]
# noyify/eamil.py
class Email(object):
def __init__(self):
pass # 发送邮件需要的前期准备
def send(self,content):
print('邮件通知:%s'%content)
# noyify/msg.py
class Msg(object):
def __init__(self):
pass # 发送短信需要的前期准备
def send(self,content):
print('短信通知:%s'%content)
# noyify/wechat.py
class WeChat(object):
def __init__(self):
pass # 发送微信需要的前期准备
def send(self,content):
print('微信通知:%s'%content)
# noyify/__init__.py
import settings
import importlib
def send_all(content):
for path in settings.NOTIFY_LIST:
module_name,cls_name=path.rsplit('.',maxsplit=1) # 因为import最小单位只能到文件,因此需要将文件路径和类名分隔开
module = importlib.import_module(module_name) # 通过importlib导入文件
cls = getattr(module,cls_name) # 通过反射获取文件中类
obj = cls()
obj.send(content)
# start.py
from notify import *
send_all('明天放假')
以钓鱼网站的转账为例:
因此,CSRF就是为了解决这种问题
name="csrfmiddlewaretoken"
<form action="" method="post">
{% csrf_token %}
<p>username:<input type="text" name="username"></p>
<p>target_account:<input type="text" name="target_user"></p>
<p>money:<input type="text" name="money"></p>
<input type="submit">
</form>
<!--浏览器可以看到的隐藏的input标签-->
<input type="hidden" name="csrfmiddlewaretoken" value="rJ47FeK9T55wavvVJGY6UxdM1kTMHhTqotGfaXjXIK8Ahz2Uvs02yR9T8bBn5q2D">
data:{'username':'jason','csrfmiddlewaretoken':$('input[name="csrfmiddlewaretoken"]').val()},
data:{'username':'jason','csrfmiddlewaretoken':'{{ csrf_token }}'},
通过获取返回的cookie中字符串,放置在请求头中
$.ajax({
url: "/cookie_ajax/",
type: "POST",
headers: {"X-CSRFToken": $.cookie('csrftoken')}, // 从Cookie取csrf_token,并设置ajax请求头
data: {"username": "Q1mi", "password": 123456},
success: function (data) {
console.log(data);
}
})
# jswenjian
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
from django.views.decorators.csrf import csrf_exempt,csrf_protect
# 1. csrf_protect方式全都可以 跟普通的装饰器装饰CBV一致
# @method_decorator(csrf_protect,name='post') # 可以
class MyIndex(views.View):
@method_decorator(csrf_protect)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request,*args,**kwargs)
def get(self,request):
return render(request,'transfer.html')
# @method_decorator(csrf_protect) # 可以
def post(self,request):
return HttpResponse('OK')
# 2. csrf_exempt这个装饰器只能给dispatch装才能生效
# @method_decorator(csrf_exempt,name='post') # csrf_exempt不支持该方法
@method_decorator(csrf_exempt,name='dispatch') # 生效
class MyIndex(views.View):
# @method_decorator(csrf_exempt) # 生效
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request,*args,**kwargs)
def get(self,request):
return render(request,'transfer.html')
# @method_decorator(csrf_exempt,name='post') # csrf_exempt不支持该方法
def post(self,request):
return HttpResponse('OK')
from django.contrib import auth
from django.contrib.auth.models import User
# User.objects.create(username=username,password=password) # 不可用 密码不是加密的
# User.objects.create_user(username=username,password=password) # 创建普通用户 密码自动加密
# User.objects.create_superuser(username=username,password=password,email='123@qq.com') # 创建超级用户 需要邮箱数据
from django.contrib import auth
user_obj = auth.authenticate(request,username=username,password=password)
# 必须传用户名和密码两个参数缺一不能
auth.login(request,user_obj)
# 只要这句话执行了 后面在任意位置 只要你能拿到request你就可以通过request.user获取到当前登录的用户对象
request.user.is_authenticated()
request.user.check_password(old_password)
request.user.set_password(new_password)
request.user.save() # 千万不要忘了
auth.logout(request)
from django.contrib.auth.decorators import login_required
# 局部配置
@login_required(login_url='/login/')
def index(request):
pass
#全局配置
settings配置文件中 直接配置
LOGIN_URL = '/login/'
@login_required
def index(request):
pass
# 如果全局配置了 局部也配置 以局部的为准
通过一对一外键字段关系扩展字段
class UserDetail(models.Model):
phone = models.BigIntegerField()
user = models.OneToOneField(to='User')
# module.py
from django.contrib.auth.models import AbstractUser
class Userinfo(AbstractUser):
phone = models.BigIntegerField()
register_time = models.DateField(auto_now_add=True)
# settings.py
AUTH_USER_MODEL = 'app01.Userinfo' # 应用名.表名
实现思路:先加载全局配置给对象设置,然后在加载局部配置 再给对象设置,一旦有重复的项 后者覆盖前者
基于settings源码设计思想启发,实现文件插拔式设计
# conf/settings.py
NAME = '我是暴露给用户的自定义配置'
# lib/conf/globa_settings.py
NAME = '我是项目默认的配置文件'
# lib/conf/__init__.py
import importlib
from lib.conf import global_settings
import os
class Settings(object):
def __init__(self):
for name in dir(global_settings):
if name.isupper():
setattr(self, name, getattr(global_settings, name))
# 获取暴露给用户的配置文件字符串路径
module_path = os.environ.get('xxx')
md = importlib.import_module(module_path) # md = settings
for name in dir(md):
if name.isupper():
k = name
v = getattr(md,name)
setattr(self,k,v)
settings = Settings()
# start.py
import os
import sys
BASE_DIR = os.path.dirname(__file__)
sys.path.append(BASE_DIR)
if __name__ == '__main__':
# os.environ.setdefault('xxx','conf.settings')
os.environ['xxx'] = 'conf.settings' # environ是一个字符串所对应环境的映像对象
from lib.conf import settings
print(settings.NAME)
标签:begin ted token decorator lis auto 方式 不可 函数
原文地址:https://www.cnblogs.com/1012zlb/p/12005976.html