返回顶部

django 知识概括 (四)

auth模块的知识点

1. 创建超级用户
python manage.py createsuperuser

from django.contrib import auth

2. auth.authenticate(username=username, password=pwd)

验证用户名和密码
如果验证成功,得到的是一个用户对象
如果验证失败,得到的是匿名用户

3. auth.login(request, user)
将验证过的用户 赋值给 request.user属性

4. auth.logout(request)

request.session.flush()
将session数据都删除,并且Cookie也失效

from django.contrib import auth
from django.contrib.auth.decorators import login_required

def login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        pwd = request.POST.get("password")
        # 如何判断用户名和密码对不对
        user = auth.authenticate(username=username, password=pwd)
        if user:
            ret = user.is_authenticated()
            print(ret)
            print("-" * 120)

            # 将登录的用户封装到request.user
            auth.login(request, user)
            return redirect("/index/")
    return render(request, "login.html")


@login_required
def index(request):
    print(request.user.username)
    print("=" * 120)
    ret = request.user.is_authenticated()
    print(ret)
    return render(request, "index.html")




def logout(request):
    auth.logout(request)
    return redirect("/login/")

 

基于中间键做的权限

# by luffycity.com
import re
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import  HttpResponse,redirect

class ValidPermission(MiddlewareMixin):

    def process_request(self,request):


        # 当前访问路径
        current_path = request.path_info

        # 检查是否属于白名单
        valid_url_list=["/login/","/reg/","/admin/.*"]

        for valid_url in valid_url_list:
            ret=re.match(valid_url,current_path)
            if ret:
                return None


        # 校验是否登录

        user_id=request.session.get("user_id")

        if not user_id:
            return redirect("/login/")


        # 校验权限
        permission_list = request.session.get("permission_list",[])  # ['/users/', '/users/add', '/users/delete/(\\d+)', 'users/edit/(\\d+)']

        flag = False
        for permission in permission_list:

            permission = "^%s$" % permission

            ret = re.match(permission, current_path)
            if ret:
                flag = True
                break
        if not flag:
            return HttpResponse("没有访问权限!")

        return None

 

 

osi七层模型

人们按照分工不同把互联网协议从逻辑上划分了层级:

  应用层,传输层,网络层,数据链路层,物理层

       应用层,会话层,表示层,传输层,网络层,数据链路层,物理层






































 

posted @ 2018-10-12 00:47  Crazymagic  阅读(102)  评论(0编辑  收藏  举报