table of Contents
Django framework 9
1.django request lifecycle
2.django Middleware
It is the gateway to django
As long as the global related functions, should be considered with django middleware to help you complete
Global user identity verification
Global user access frequency check
User access to blacklist
Whitelist user access
django default seven middleware
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',
]
django supports user-defined middleware
class SessionMiddleware(MiddleWareMixin):
def process_request(self, request):
def process_response(self, request, response):
class CsrfViewMiddleware(MiddlewareMixin):
def process_request(self, request):
def process_view(self, request, callback, callback_args, callback_kwags):
def process_respose(self, request, response):
class AuthentiactionMiddleware(MiddlewareMixin):
def process_request(self, request):
django running user-defined method to the middleware and the user can customize the five exposure
Master:
process_request:
When the request is executed in the configuration file are sequentially registered in the order from the intermediate down inside each intermediate process_request method, if not skip to the next
The same level of return does not perform all process_response
process_response:
Response time will go sequentially performed in accordance with the profile registered in the middleware sequentially from the bottom inside process_response each broker, the method must have two parameters, and the need to return response parameter, if your own internal returns HttPResponse object will return the contents of the user's browser to replace it with your own
Learn:
process_view
Trigger match before routing the successful implementation of the view function
process_template_response
View objects must be returned by the function attribute corresponding to render the render method
def index(request):
def render():
return HttpResponse('你好啊')
obj = HttpResopnse("index")
obj.render = render
return obj
process_exception
When the view function automatically triggers an error
3.csrf CSRF
Phishing sites
Nature set up a website with normal exactly the same page, the user complete the transfer function on the page, submit the transfer request indeed, towards the end of normal service site, the only difference lies in the different accounts receivable person
How crsf check form form
You only need to write a form in your form
{% csrf_token %}
ajax check how csrf
第一种方式 自己手动获取
data:{'username':'jason', 'csrfmiddlewaretoken':$('input[name="csrfmiddlewaretoken"]').val()}
第二种方式 利用模板语法
data:{'username':'jason','crsfmiddlewaretoken':'{{ csrf_token }}'}
第三种 通用方式 引入外部js文件 官网提供的方式
<% load static %>
<script src="{% static 'myset.js' %}"></script>
data: {'username': 'jason'}
csrf related decorator
When we have a whole website check csrf the time, so a few view function does not check
When we do not check crsf the site as a whole, let a few view function check
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.views import View9
from django.utils.decorators import method_decorator
# @method_decorator(csrf_protect,name='post') # 第二种指名道姓的给类中某个方法装
# @method_decorator(csrf_exempt,name='post') # csrf_exempt 第二种方式不行
@method_decorator(csrf_exempt,name='dispatch') # 可以!!!
class MyHome(View): # APIView
# @method_decorator(csrf_protect) # 第三种 类中所有的方法都装
# @method_decorator(csrf_exempt) # csrf_exempt 第三种方式可以
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request,*args,**kwargs)
def get(self,request):
return HttpResponse('get')
# @method_decorator(csrf_protect) # 第一种方式
# @method_decorator(csrf_exempt) # csrf_exempt 第一种方式不行
def post(self,request):
return HttpResponse('post')
Add to cbv decorator recommended template method_decorator
Write our own decorators and consistent usage csrf_protect
Csrf_exempt only exception is an exception to the dispatch method installed
4.auth authentication module
django own user-related functional modules TABLE auth_user
How to create a super-user:
createsupperuser
Import module
from django.contrib mport auth
from django.contrib.auth.models import User
auth method Daquan
1. Create a user
User.objects.create() # 密码都是明文
User.objects.createuser() # 创建普通用户
User.objects.createsuperuser() # 创建超级用户,邮箱要给数据
2. Verify the username and password are correct
auth.authenticate(username=username,password=password) #密码和用户名两个一个都不能少
# 该方法当用户名和密码正确的时候返回用户对象 不正确返回none
3. Save the user login status
auth.login(request, user_obj)
# 这句执行完以后 request.user获取当前登录的用户对象
4. How to determine the current user is logged on and how to get the current logged-on user objects
request.user.is_authenticcated() # 判断是否登录
request.user # 登录用户对象
5. check whether the user is logged
form django.contrib.auth.deorators import login_required
# 局部配置
@login_required(login_url='/login/')
def xxx(request):
return HttpResponse('xxx页面')
# 全局配置
配置文件中写以下代码
LOGIN_URL = '/login/'
@login_required
def xxx(request):
return HttpResponse('xxx页面')
如果两个都设置了,那么优先执行局部配置
6. Change Password
request.user.check_password(old_password) # 校验原密码是否正确
request.User.set_password(new_pssword)
request.user.save() # 一定要保存
7. logout function
auth.logout(request)
How to extend auth_user table
1. Use one table relationships
2. Using class inheritance
# 1 类的继承
from django.contrib.auth.models import User,AbstractUser
# Create your models here.
class Userinfo(AbstractUser):
phone = models.BigIntegerField()
avatar = models.FileField()
# 扩展的字段 尽量不要与原先表中的字段冲突
# 2 配置文件
AUTH_USER_MODEL = '应用名.表名'
"""
django就会将userinfo表来替换auth_user表
并且之前auth模块所有的功能不变 参照的也是userinfo表
"""
5.BBS table design
用户表
继承auth_user表
phone
avatar
register_time
个人站点表
站点名称
站点标题
站点样式
文章分类表
分类名
文章标签表
标签名
文章表
文章标题
文章摘要
文章详情
创建日期
点赞点踩表
user 一对多用户
article 一对多文章
is_up 布尔值字段
文章评论表
user 一对多用户
article 一对多文章
content 普通字段
create_time 评论日期
parent ForeginKey(to='文章评论表')
parent ForeginKey(to='self')
根评论子评论