您好,登錄后才能下訂單哦!
這篇文章主要介紹django_auth的示例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
django內置了用戶認證系統,處理用戶賬戶、用戶組、權限,基于cookie的session,且內置了一些快捷函數;
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',
]
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: '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''
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
<!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>
認證的用戶才能登錄到指定頁面,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')
http無狀態,cookie讓http請求時攜帶狀態,cookie保存在browser緩存中,和域名有關;
session是基于cookie來做的,只不過保存了一個session id,所有其它內容都在server端存儲,用來鑒別用戶是否登錄及其它信息,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
用單獨的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權限系統實現了全局的授權機制(即,是否有某張表的權限(增加、編輯、刪除)),沒有提供對象級別的授權(即沒有實現表中某個對象的權限(增加、編輯、刪除));
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");
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");
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()
<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
例,用戶組權限:
>>> 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的示例分析”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。