本文实例讲述了Django自定义认证方式。分享给大家供大家参考,具体如下:
创建登录应用
首先创建一个新的login app,用来存放认证用到代码
1
|
python manage.py startapp login |
修改settings.py中的认证项
1
2
3
|
AUTHENTICATION_BACKENDS = ( 'login.auth.UsernamePasswordAuth' , ) |
自定义认证类
在login app下创建auth.py文件,内容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#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程序设计有所帮助。