溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

django_auth的示例分析

發(fā)布時(shí)間:2021-11-24 14:53:42 來源:億速云 閱讀:136 作者:小新 欄目:編程語言

這篇文章主要介紹django_auth的示例分析,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

auth

django內(nèi)置了用戶認(rèn)證系統(tǒng),處理用戶賬戶、用戶組、權(quán)限,基于cookie的session,且內(nèi)置了一些快捷函數(shù);

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的子類;

創(chuàng)建用戶:

>>> 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: 'test'>

>>> user.is_superuser

True

>>> user.is_staff

True

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

>>> jowin

<User: 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、認(rèn)證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)   #認(rèn)證成功返回用戶名,認(rèn)證失敗返回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

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

    <h2>index</h2>

</body>

</html>

mysite/blog/templates/blog/login.html

<h2>login form</h2>

<form method="post" action="">

    {% csrf_token %}

    <input type="text" name="username" id="username">

    <input type="password" name="password">

    <input type="submit" value="submit">

</form>

authentication web:

認(rèn)證的用戶才能登錄到指定頁(yè)面,next=后跟的是登陸成功后的跳轉(zhuǎn)url;

未認(rèn)證的跳到登錄頁(yè)(用戶沒有登錄會(huì)重定向到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,手動(dòng)認(rèn)證:

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無狀態(tài),cookie讓http請(qǐng)求時(shí)攜帶狀態(tài),cookie保存在browser緩存中,和域名有關(guān);

session是基于cookie來做的,只不過保存了一個(gè)session id,所有其它內(nèi)容都在server端存儲(chǔ),用來鑒別用戶是否登錄及其它信息,session要比cookie安全;

{

'_stream': <django.core.handlers.wsgi.LimitedStream object at 0x00000000040D27B8>,

'csrf_processing_done': True,

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

'_read_started': False,

'_post_parse_error': False,

'content_type': 'text/plain',

'_cached_user': <User: jowin>,

'path': '/blog/',

'session': <django.contrib.sessions.backends.db.SessionStore object at 0x00000000040D27F0>,

'user': <SimpleLazyObject: <User: jowin>>,

'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': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x00000000040D2A58>,

'environ': {...},

'META': {...}

}

request.COOKIES

request.session

from django.contrib.sessions.models import Session

自定義User model:

用單獨(dú)的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文件再執(zhí)行

python manage.py migrate

授權(quán):

django權(quán)限系統(tǒng)實(shí)現(xiàn)了全局的授權(quán)機(jī)制(即,是否有某張表的權(quán)限(增加、編輯、刪除)),沒有提供對(duì)象級(jí)別的授權(quán)(即沒有實(shí)現(xiàn)表中某個(gè)對(duì)象的權(quán)限(增加、編輯、刪除));

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);

例,用戶權(quán)限:

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

>>> User.objects.all()

<QuerySet []>

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

>>> User.objects.all()

<QuerySet [<User: jowin>]>

>>> 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('<app_label>.<codename>')

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

例,用戶組權(quán)限:

>>> 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')   #用戶繼承用戶組的權(quán)限

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的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI