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实现单链表的方法示例

python实现单链表的方法示例

前言 首先说下线性表,线性表是一种最基本,最简单的数据结构,通俗点讲就是一维的存储数据的结构。 线性表分为顺序表和链接表: 顺序表示指的是用一组地址连续的存储单元依次存储线性表的数...

详解PyTorch中Tensor的高阶操作

详解PyTorch中Tensor的高阶操作

条件选取:torch.where(condition, x, y) → Tensor 返回从 x 或 y 中选择元素的张量,取决于 condition 操作定义: 举个例子:...

python同义词替换的实现(jieba分词)

python同义词替换的实现(jieba分词)

TihuanWords.txt文档格式注意:同一行的词用单个空格隔开,每行第一个词为同行词的替换词。年休假 年假 年休究竟 到底回家场景 我回来了代码import jieba...

使用Python实现毫秒级抢单功能

使用Python实现毫秒级抢单功能

目录: 引言 环境 需求分析&前期准备 淘宝购物流程回顾 秒杀的实现 代码梳理 总结 0 引言 年中购物618大狂欢开始了,各大电商又开始了大力...

python中字符串内置函数的用法总结

capitalize() 首字母大写 a='someword' b=a.capitalize() print(b) —>Someword casefold()&l...