auth module + plug-thinking

auth module + plug-thinking

A, auth module

django to facilitate the achievement of user functions, including landing modify the registration cancellation information provided auth module, simple operation.

1.1 common method

Supervisor:

# run manage.py Task:
createsuperuser

authenticate (): user authentication is successful, will return to the User object, unsuccessful return None

from django.contrib import auth

def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        # 验证用户是否存在
        user_obj = auth.authenticate(username=username, password=password)

login (HttpRequest, user): a receiving HttpRequest object, and after a verification object associated with the user session data is generated for the rear end;

# 保存登录信息
auth.login(request,user_obj)   #执行后,可以通过request.User获取到登录用户对象

is_authenticated (): determine whether the current user login;

request.user.is_authenticated()

Get the current user:

user_obj = request.user

loginout (request): accepting a HttpRequest, clear information on the current session request. If the user is not logged, it will not error;

from django.contrib.auth import logout

def llogout(request):
    logout(request)

login_required (): login authentication decorator;

from django.contrib.auth.decorators importlogin_requird

# 局部配置
@login_required(login_url = '/xxx/')

# 全局配置
@login_required
def home(request):
    return HttpResponse('home页面')
    
'''
当用户没有登录的情况下 跳转的url有两种配置方式:
    1.在装饰器括号内通过login_url参数局部指定
    2.全局配置  用户没有登录的情况下 所有的视图统一跳转到一个url
'''

create_user (): Create a user;

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=passwore, email='[email protected]')

check_password (password): Check the password correctly returns Ture, an error is False;

set_password (password): Set a new password;

@login_required
def set_password(request):
    if request.method == 'POST':
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        # 校验原密码
        is_right() = request.user.check_password(old_password)
        if is_right:
            # 设置新密码
            request.user.set_password(new_password) # 此时值保存在内存中
            request.user.save()  # save()后才保存在数据库中
            return redirect('/login/')
    return render(request, 'set_password.html', locals())

1.2 extend the default table

auth module has built-in tables and fields, but only the frame, use the other fields will also be required information. It can be a key one to one association table auth_user table, as long as you can inherit AbstractUser.

from django.contrib.auth.models import AbstractUser

class UserInfo(AbstractUser)  # 注意,自定义表中字段不能与auth_user表中的字段冲突
    phone = models.BigIntegerField()
    register_time = models.DataField(auto_now_add=Ture)
    
def __str__(self):
    return self.username

Note: the extended auth_user table must be configured in the manner described above in settings.py:

AUTH_USER_MODEL = "app名.Userinfo"

Note again: Once you develop a new table, you need to rebuild the table in the database, can not continue to use the default auth_user the table.

Second, the reference django middleware configuration, implement the functions of the plug-in design

django middleware can filter information on demand, when this requirement is not required, you can put this in the settings.py screening requirements written off, it can be achieved. This provides a method for encapsulating functionality, such as a broadcast system that uses text messaging, e-mail a variety of methods, QQ and other published information, you can log out by implementing the method in settings or to add new methods to increase.

Ideas: The various functions of the information transmitted in the package py different file types are defined as ducks. Write function in the configuration file path the init file processing path, with getattr method, a method is provided. Add this new method, you can write methods py file then add the path in the configuration file, cancel method to write off the path to the corresponding method in the configuration file.

notify folder:

​ __init__:

import settings
import importlib

def send_all(content):
    for module_path in settings.NOTIFY_LIST:
        module, class_name = module_path.rsplit('.', maxslipt=1)
        # module = 'notify.email'  class_name = 'Email'
        mod = importlib.import_module(module)  # mod时模块名,例如email.py
        cls = getattr(mod, class_name)
        obj = cls()
        obj.send(content)

​ email.py:

class Email(object):
    def __init__(self):
        pass   # 省略相关配置操作
    
    def send(self, content):
        print('邮件通知:%s' % content)

​ msg.py:

class Msg(object):
    def __init__(self):
        pass  # 省略相关配置操作

    def send(self,content):
        print('短信通知:%s'%content)

WeChat:

class WeChat(object):
    def __init__(self):
        pass  # 省略相关配置操作

    def send(self, content):
        print('微信通知:%s' % content)

​ qq.py:

class QQ(object):
    def __init__(self):
        pass   # 省略相关配置操作

    def send(self,content):
        print('qq通知:%s'%content)

​ run.py

import notify

notify.send_all('测试信息')

​ settings.py

NOTIFY_LIST = [
    'notify.email.Email',
    # 'notify.msg.Msg',   # 注销掉msg,可以关闭短信发送消息的功能
    'notify.wechat.WeChat',
    'notify.qq.QQ',
]

Guess you like

Origin www.cnblogs.com/tangceng/p/11774370.html