In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces the example analysis of django_auth, which is very detailed and has certain reference value. Friends who are interested must finish it!
Auth
Django has built-in user authentication system to deal with user accounts, user groups, permissions, cookie-based session, and built-in some shortcut functions
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 table:
Sqlite > .schema auth_user
CREATE TABLE IF NOT EXISTS "auth_user" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT
Password varchar 128NOT 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 properties attr,from django.contrib.auth.models import User:
Is_authenticated
Is_anonymous
Username_validator
User method:
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 table, from django.contrib.auth.models import AnonmousUser:
Is a subclass of User
Create a user:
> from django.contrib.auth.models import User
> user = User.objects.create_user ('jowin','jowin@ane56.com','jowin') # side 1
> user.last_name = 'chai'
> > user.save ()
(webproject) C:\ webproject\ mysite > python manage.py createsuperuser-- username='test'-- email='test@ane56.com' # side 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 ()
Change the password:
> 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''
Log in to login, log out of logout, and authenticate 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) # user name is returned after successful authentication, and None is returned if authentication fails.
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:
Only authenticated users can log in to the specified page. Next= is followed by a jump url after a successful login.
Unauthenticated jump to the login page (users who do not log in will be redirected to the LOGIN_URL ='/ blog/login/' configured in settings.py or you can specify login_url in the decorator login_requrired ())
After logging in successfully
Square 1, use the decorator:
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/'
Party 2, manual authentication:
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 is stateless. Cookie allows http to carry status when requesting, and cookie is saved in browser cache, which is related to domain name.
Session is based on cookie, except that a session id is saved, and all other content is stored on the server side, which is used to identify whether the user is logged in and other information. Session is more secure than cookie.
{
'_ stream':
'csrf_processing_done': True
'COOKIES': {' csrftoken': '7Ew8ASc6rAcdtMyHNeXQFLybjkruuwocJSCnfoLuNz3TYMi00TNwIhAyJmsOMUNopia,' 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
Custom User model:
Use a separate app for user processing
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 # delete the db.sqlite3 file before execution if there is a problem
Python manage.py migrate
Authorization:
The django permission system implements a global authorization mechanism (that is, whether there are permissions for a table (add, edit, delete), and does not provide object-level authorization (that is, no permissions for an object in the table (add, edit, delete))
Permission table:
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 table:
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 table:
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)
For example, user permissions:
> 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) # same as 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
For example, user group permissions:
> 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) # same as sa.permissions.set ([p])
> user.has_perm ('auth.add_user') # users inherit permissions from user groups
True
Sa.permissions.set ([permission_list])
Sa.permissions.add (permission,permission,...)
Sa.permissions.remove (permission,permission,...)
Sa.permissions.clear ()
In view, use:
From django.contrib.auth.decorators import permission_required
@ permission_required ('polls.can_vote', login_url='/loginpage/')
Def my_view (request):
Pass
The above is all the content of this article "sample Analysis of django_auth". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 237
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.