Django自定义认证方式用法示例

yipeiwu_com6年前Python基础

本文实例讲述了Django自定义认证方式。分享给大家供大家参考,具体如下:

创建登录应用

首先创建一个新的login app,用来存放认证用到代码

python manage.py startapp login

修改settings.py中的认证项

AUTHENTICATION_BACKENDS = (
  'login.auth.UsernamePasswordAuth',
)

自定义认证类

在login app下创建auth.py文件,内容如下

#coding:utf-8
from django.contrib.auth.models import User
class UsernamePasswordAuth(object):
  def authenticate(self, username=None, password=None):
    print("UsernamePasswordAuth.authenticate")
    try:
      user = User.objects.get(username__iexact=username)
      if user.check_password(password):
        return user
    except User.DoesNotExist:
      return None
  def get_user(self, user_id):
    print("UsernamePasswordAuth.get_user")
    try:
      user = User.objects.get(pk=user_id)
      return user
    except User.DoesNotExist:
      return None

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python Socket编程技巧总结》、《Python URL操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

python 高效去重复 支持GB级别大文件的示例代码

如下所示: #coding=utf-8 import sys, re, os def getDictList(dict): regx = '''[\w\~`\!\@\#\...

Python将图片转换为字符画的方法

Python将图片转换为字符画的方法

最近在学习Python,看到网上用Python将图片转换成字符画便来学习一下 题目意思是,程序读入一个图片,以txt格式输出图片对应的字符画,如图所示: 以下是Python代码:...

python的staticmethod与classmethod实现实例代码

本文源于一时好奇,想要弄清出python的staticmethod()这一builtin方法的实现,查了一些资料(主要是python官方手册了)汇集于此 python在类中,有三种调用m...

python3.5 + PyQt5 +Eric6 实现的一个计算器代码

python3.5 + PyQt5 +Eric6 实现的一个计算器代码

目前可以实现简单的计算。计算前请重置,设计的时候默认数字是0,学了半天就做出来个这么个结果,bug不少。 python3.5 + PyQt5 +Eric6 在windows7 32位系统...

python开头的coding设置方法

缘起: [root@CentOS7 code]# python multi_thread_mfw.py File "multi_thread_mfw.py", line 138...