python测试开发django

前言

在开发一个网站时,经常会用到用户的注册和登陆相关的账号管理功能,auth模块是Django提供的标准权限管理系统,可以提供用户身份认证, 用户组和权限管理。

像用户注册、用户登录、用户认证、注销、修改密码等功能都不需要我们去开发,这些功能django已经早就设计好了。

auth模块
python manage.py createsuperuser

这里我的账号是root,密码是root,很显然存在数据库的密码不是明文的,而是加密后的

认证authenticate()
authenticate

from django.contrib.auth import authenticate

> python manage.py shell
>>> from django.contrib.auth.models import User
>>> from django.contrib.auth import authenticate

输入正确账号,密码,user返回root用户对象

>>> user=authenticate(username=‘root’,password=‘root’)
>>> user
<User: root>

输入错误的密码,user返回为空

>>> user=authenticate(username=‘root’,password=‘xxxx’)
>>> user
>>>

authenticate认证用户的密码是否有效, 若有效则返回代表该用户的user对象, 若无效则返回None

注册create_user
create_user
> python manage.py shell
>>> from django.contrib.auth.models import User
>>> from django.contrib.auth import authenticate

新增用户test.密码test

>>> user1=User.objects.create_user(username=‘test’,password=‘test’,email=‘283340479@qq.com’)
>>> user1.save()
>>>

save保存后,数据库查看auth_user表新增成功

修改密码set_password

当我们需要修改密码的时候,可以用set_password方法,该方法不验证用户的身份,直接修改,一般在已经登陆的时候,修改密码使用

> python manage.py shell
>>> from django.contrib.auth.models import User
>>> from django.contrib.auth import authenticate
>>> user=authenticate(username=‘test’,password=‘test’)

设置新密码

>>> user.set_password(‘123456’)
>>> user.save()

修改成功后使用新密码登陆

>>> user=authenticate(username=‘test’,password=‘test’)
>>> user.set_password(‘123456’)

当密码错误的时候,user返回为空,使用user.set_password(‘123456’)会直接抛异常,所以修改密码的时候,一般先判断下

>>> user=authenticate(username=‘test’,password=‘test’)

密码不对,user为空抛异常

>>> user.set_password(‘123456’)
Traceback (most recent call last):
File “<console>”, line 1, in <module>
AttributeError: ‘NoneType’ object has no attribute ‘set_password’

加判断

>>> user=authenticate(username=‘test’,password=‘test’)
>>> user
>>> if user is not None:
… user.set_password(‘123456’)
… user.save()

>>>

登陆login

用户登陆功能,有给专门的login函数,它可以在session中添加SESSION_KEY

from django.contrib.auth import login

login(request, user)authenticate(username=username, password=password)

login(request, user)

is_active
from django.contrib.auth import login, authenticate
def login_view(request):

‘’‘session登陆&#39;&#39;&#39;<br/>
user = authenticate(username=&#39;test&#39;, password=&#39;test&#39;)<br/>
if user is not None:<br/>
    if user.is_active:<br/>
        login(request, user)<br/>

退出登陆

logout会清除request中的user信息, 并刷新session

from django.contrib.auth import logout
def logout_view(request):

&#39;&#39;&#39;退出登陆&#39;&#39;&#39;<br/>
logout(request)<br/>