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程序设计有所帮助。

相关文章

Django中处理出错页面的方法

花几分钟时间欣赏一下我们写好的Web应用程序,然后我们再来搞点小破坏。 我们故意在 views.py 文件中引入一项 Python 错误,注释掉 hours_ahead 视图中的 off...

python分析apache访问日志脚本分享

#!/usr/bin/env python # coding=utf-8 #---------------------------------------------------...

python实现删除文件与目录的方法

本文实例讲述了python实现删除文件与目录的方法。分享给大家供大家参考。具体实现方法如下: os.remove(path) 删除文件 path. 如果path是一个目录, 抛出 OSE...

Python基于sftp及rsa密匙实现远程拷贝文件的方法

本文实例讲述了Python基于sftp及rsa密匙实现远程拷贝文件的方法。分享给大家供大家参考,具体如下: 如果两台服务器之间使用了RSA秘钥免密码登录的方式,可以先查找出rsa秘钥的对...

python和opencv实现抠图

本文实例为大家分享了python实现抠图的具体代码,供大家参考,具体内容如下 其中使用了opencv中的grabcut方法 直接上代码 # encoding:utf-8 # 图像提取...