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实现的knn算法示例

Python实现的knn算法示例

本文实例讲述了Python实现的knn算法。分享给大家供大家参考,具体如下: 代码参考机器学习实战那本书: 机器学习实战 (Peter Harrington著) 中文版 机器学习实战 (...

Python break语句详解

Python break语句详解

Python break语句,就像在C语言中,打破了最小封闭for或while循环。break语句用来终止循环语句,即循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环...

对python3 sort sorted 函数的应用详解

python3 sorted取消了对cmp的支持。 python3 帮助文档: sorted(iterable,key=None,reverse=False) key接受一个函数,...

django 使用 request 获取浏览器发送的参数示例代码

获取数据(四种方式) 1. url: 需要正则去匹配     url(r'^index/(num)/$',view.index)   &...

django基于restframework的CBV封装详解

一.models数据库映射 from django.db import models # Create your models here. class Book(models.Mo...