django_auth的示例分析

这篇文章主要介绍django_auth的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:主机域名雅安服务器托管、营销软件、网站建设、郴州网站维护、网站推广。

auth

django内置了用户认证系统,处理用户账户、用户组、权限,基于cookie的session,且内置了一些快捷函数;

requirement:

mysite/mysite/settings.py

INSTALLED_APPS = [

    'blog.apps.BlogConfig',

    'publish.apps.PublishConfig',

    'bootstrap3',

    'books.apps.BooksConfig',

    'polls.apps.PollsConfig',

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

]

MIDDLEWARE = [

    'django.middleware.security.SecurityMiddleware',

    'django.contrib.sessions.middleware.SessionMiddleware',

    'django.middleware.common.CommonMiddleware',

    'django.middleware.csrf.CsrfViewMiddleware',

    'django.contrib.auth.middleware.AuthenticationMiddleware',

    'django.contrib.messages.middleware.MessageMiddleware',

    'django.middleware.clickjacking.XFrameOptionsMiddleware',

]

user表:

sqlite> .schema auth_user

CREATE TABLE IF NOT EXISTS "auth_user" (

"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,

"password" varchar(128) NOT NULL,

"last_login" datetime NULL,

 "is_superuser" bool NOT NULL,

"first_name" varchar(30) NOT NULL,

"last_name" varchar(30) NOT NULL,

"email" varchar(254) NOT NULL,

"is_staff" bool NOT NULL,

"is_active" bool NOT NULL,

"date_joined" datetime NOT NULL,

"username" varchar(150) NOT NULL UNIQUE);

user表属性attr,from django.contrib.auth.models import User:

is_authenticated

is_anonymous

username_validator

user表方法:

get_username

get_full_name

get_short_name

set_password

check_password

set_unusable_password

has_usable_password

get_group_permissions

get_all_permissions

has_perm

has_module_perms

emial_user

anonmoususer表,from django.contrib.auth.models import AnonmousUser:

是User的子类;

创建用户:

>>> from django.contrib.auth.models import User

>>> user = User.objects.create_user('jowin','jowin@ane56.com','jowin')   #方1

>>> user.last_name = 'chai'

>>> user.save()

(webproject) C:\webproject\mysite>python manage.py createsuperuser --username='test' --email='test@ane56.com'   #方2

Password:

Password (again):

This password is too short. It must contain at least 8 characters.

This password is too common.

Password:

Password (again):

Superuser created successfully.

>>> user=User.objects.get(id=2)

>>> user

>>> user.is_superuser

True

>>> user.is_staff

True

>>> jowin=User.objects.get(id=1)

>>> jowin

>>> jowin.is_superuser=True

>>> jowin.is_staff=True

>>> jowin.save()

更改密码:

>>> from django.contrib.auth.models import User

>>> u = User.objects.get(username='jowin')

>>> u.set_password('jowin')

>>> u.save()

(webproject) C:\webproject\mysite>python manage.py changepassword 'test'

Changing password for user ''test''

Password:

Password (again):

Password changed successfully for user ''test''

登录login、登出logout、认证authenticate:

mysite/blog/views.py

from django.contrib.auth import authenticate, login, logout

from django.http import HttpResponse

from django.contrib.auth.decorators import login_required

def auth_login(request):

    if request.method == 'POST':

        username = request.POST.get('username')

        password = request.POST.get('password')

        user = authenticate(username=username, password=password)   #认证成功返回用户名,认证失败返回None

        if user:

            login(request, user)

            return HttpResponse('login ok')

        else:

            return HttpResponse('login error')

    return render(request, 'blog/login.html')

def auth_logout(request):

    logout(request)

    return HttpResponse('logout success')

@login_required   #@login_required()

def index(request):

    return render(request, 'blog/index.html')

mysite/blog/templates/blog/index.html

   

    Title

   

index

mysite/blog/templates/blog/login.html

login form

    {% csrf_token %}

   

   

   

authentication web:

认证的用户才能登录到指定页面,next=后跟的是登陆成功后的跳转url;

未认证的跳到登录页(用户没有登录会重定向到settings.py中配置的LOGIN_URL = '/blog/login/'也可在装饰器login_requrired()中指定login_url);

登录成功后

方1,用装饰器:

mysite/blog/views.py

from django.contrib.auth.decorators import login_required

@login_required

@login_required(redirect_field_name='go', login_url="/blog/login")

mysite/mysite/settings.py

LOGIN_URL = '/blog/login/'

方2,手动认证:

def index(request):

    if not request.user.is_authenticated:

        return redirect(''.format('/blog/login', request.path))

    else:

        # pass   #do_something()

        return HttpResponse('ok')

Cookie、Session:

http无状态,cookie让http请求时携带状态,cookie保存在browser缓存中,和域名有关;

session是基于cookie来做的,只不过保存了一个session id,所有其它内容都在server端存储,用来鉴别用户是否登录及其它信息,session要比cookie安全;

{

'_stream': ,

'csrf_processing_done': True,

'COOKIES': {'csrftoken': '7Ew8ASc6rAcdtMyHNeXQFLybjkruuwocJJSCnfoLuNz3TYMi00TNwIhAyJmsOMUN', 'sessionid': 'j1ta2w8fj42fnv6928s0bz31abeso9q2'},

'_read_started': False,

'_post_parse_error': False,

'content_type': 'text/plain',

'_cached_user': ,

'path': '/blog/',

'session': ,

'user': >,

'path_info': '/blog/',

'method': 'GET',

'resolver_match': ResolverMatch(func=blog.views.index,

args=(),

kwargs={},

url_name=index,

app_names=['blog'],

namespaces=['blog']),

'content_params': {},

'_messages': ,

'environ': {...},

'META': {...}

}

request.COOKIES

request.session

from django.contrib.sessions.models import Session

自定义User model:

用单独的app作用户处理;

mysite/users/models.py

from django.db import models

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):

    USER_ROLE_CHOICES = (

        ('SU', 'SuperUser'),

        ('GA', 'GroupAdmin'),

        ('CU', 'CommonUser'),

    )

    name = models.CharField(max_length=80)

    uuid = models.CharField(max_length=100)

    role = models.CharField(max_length=2, choices=USER_ROLE_CHOICES, default='CU')

    ssh_key_pwd = models.CharField(max_length=200)

    def __str__(self):

        return self.name

mysite/mysite/settings.py

AUTH_USER_MODEL = 'users.User'

python manage.py makemigrations   #如有问题删除db.sqlite3文件再执行

python manage.py migrate

授权:

django权限系统实现了全局的授权机制(即,是否有某张表的权限(增加、编辑、删除)),没有提供对象级别的授权(即没有实现表中某个对象的权限(增加、编辑、删除));

permission表:

from django.contrib.auth.models import Permission

sqlite> .schema auth_permission

CREATE TABLE IF NOT EXISTS "auth_permission" (

"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,

"content_type_id" integer NOT NULL REFERENCES "django_content_type" ("id"),

"codename" varchar(100) NOT NULL,

"name" varchar(255) NOT NULL);

CREATE UNIQUE INDEX "auth_permission_content_type_id_codename_01ab375a_uniq" ON "auth_permission" ("content_type_id", "codename");

CREATE INDEX "auth_permission_content_type_id_2f476e4b" ON "auth_permission" ("content_type_id");

contenttype表:

from django.contrib.auth.models import ContentType

sqlite> .schema django_content_type

CREATE TABLE IF NOT EXISTS "django_content_type" (

"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,

"app_label" varchar(100) NOT NULL,

"model" varchar(100) NOT NULL);

CREATE UNIQUE INDEX "django_content_type_app_label_model_76bd3d3b_uniq" ON "django_content_type" ("app_label", "model");

group表:

from django.contrib.auth.models import Group

sqlite> .schema auth_group

CREATE TABLE IF NOT EXISTS "auth_group" (

"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,

"name" varchar(80) NOT NULL UNIQUE);

例,用户权限:

>>> from django.contrib.auth.models import User,Permission,ContentType

>>> User.objects.all()

>>> user = User.objects.create_user(username='jowin',email='jowin@ane56.com')

>>> User.objects.all()

]>

>>> p = Permission.objects.get(codename='add_question')

>>> user = User.objects.get(id=1)

>>> user.user_permissions.add(p)   #同user.user_permissions.set([p])

>>> user.has_perm('polls.add_question')   #has_perm('.')

True

>>> ct = ContentType.objects.get(app_label='polls',model='choice')

>>> p = Permission.objects.create(name='Can vote',codename='can_vote',content_type=ct)

>>> user.user_permissions.add(p)

>>> user.has_perm('polls.can_vote')

True

例,用户组权限:

>>> from django.contrib.auth.models import User,Permission,Group

>>> sa = Group.objects.create(name='sa')

>>> user = User.objects.get(id=1)

>>> sa.user_set.add(user)

>>> sa.save()

>>> p = Permission.objects.get(codename='add_user')

>>> sa.permissions.add(p)   #同sa.permissions.set([p])

>>> user.has_perm('auth.add_user')   #用户继承用户组的权限

True

sa.permissions.set([permission_list])

sa.permissions.add(permission,permission,...)

sa.permissions.remove(permission,permission,...)

sa.permissions.clear()

view中使用:

from django.contrib.auth.decorators import permission_required

@permission_required('polls.can_vote', login_url='/loginpage/')

def my_view(request):

         pass

以上是“django_auth的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!


文章名称:django_auth的示例分析
链接地址:http://azwzsj.com/article/gcsiee.html