小編給大家分享一下Django用戶認(rèn)證系統(tǒng)中組與權(quán)限的示例分析,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
站在用戶的角度思考問(wèn)題,與客戶深入溝通,找到佛山網(wǎng)站設(shè)計(jì)與佛山網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗(yàn),讓設(shè)計(jì)與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個(gè)性化、用戶體驗(yàn)好的作品,建站類型包括:成都網(wǎng)站建設(shè)、成都做網(wǎng)站、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣、空間域名、網(wǎng)站空間、企業(yè)郵箱。業(yè)務(wù)覆蓋佛山地區(qū)。Django的權(quán)限系統(tǒng)很簡(jiǎn)單,它可以賦予users或groups中的users以權(quán)限。
Django admin后臺(tái)就使用了該權(quán)限系統(tǒng),不過(guò)也可以用到你自己的代碼中。
User對(duì)象具有兩個(gè)ManyToManyField字段,groups和user_permissions
groups = models.ManyToManyField(Group, verbose_name=_('groups'), blank=True, help_text=_('The groups this user belongs to. A user will ' 'get all permissions granted to each of ' 'their groups.'), related_name="user_set", related_query_name="user") user_permissions = models.ManyToManyField(Permission, verbose_name=_('user permissions'), blank=True, help_text=_('Specific permissions for this user.'), related_name="user_set", related_query_name="user")
可以像其它的django Model一樣來(lái)訪問(wèn)他們:
myuser.groups = [group_list] myuser.groups.add(group, group, ...) myuser.groups.remove(group, group, ...) myuser.groups.clear() myuser.user_permissions = [permission_list] myuser.user_permissions.add(permission, permission, ...) myuser.user_permissions.remove(permission, permission, ...) myuser.user_permissions.clear()
權(quán)限Permissions
權(quán)限是作為一個(gè)Model存在的,建立一個(gè)權(quán)限就是創(chuàng)建一個(gè)Permission Model的實(shí)例。
@python_2_unicode_compatible class Permission(models.Model): """ The permissions system provides a way to assign permissions to specific users and groups of users. The permission system is used by the Django admin site, but may also be useful in your own code. The Django admin site uses permissions as follows: - The "add" permission limits the user's ability to view the "add" form and add an object. - The "change" permission limits a user's ability to view the change list, view the "change" form and change an object. - The "delete" permission limits the ability to delete an object. Permissions are set globally per type of object, not per specific object instance. It is possible to say "Mary may change news stories," but it's not currently possible to say "Mary may change news stories, but only the ones she created herself" or "Mary may only change news stories that have a certain status or publication date." Three basic permissions -- add, change and delete -- are automatically created for each Django model. """ name = models.CharField(_('name'), max_length=255) content_type = models.ForeignKey(ContentType) codename = models.CharField(_('codename'), max_length=100) objects = PermissionManager() class Meta: verbose_name = _('permission') verbose_name_plural = _('permissions') unique_together = (('content_type', 'codename'),) ordering = ('content_type__app_label', 'content_type__model', 'codename') def __str__(self): return "%s | %s | %s" % ( six.text_type(self.content_type.app_label), six.text_type(self.content_type), six.text_type(self.name)) def natural_key(self): return (self.codename,) + self.content_type.natural_key() natural_key.dependencies = ['contenttypes.contenttype']
字段fields
name:必需。50個(gè)字符或更少,例如,'Can Vote‘
content_type:必需,一個(gè)對(duì)于django_content_type數(shù)據(jù)庫(kù)table的引用,table中含有每個(gè)應(yīng)用中的Model的記錄。
codename:必需,100個(gè)字符或更少,例如,'can_vote'。
如果要為某個(gè)Model創(chuàng)建權(quán)限:
from django.db import models class Vote(models.Model): ... class Meta: permissions = (("can_vote", "Can Vote"),)
如果這個(gè)Model在應(yīng)用foo中,則權(quán)限表示為'foo.can_vote',檢查某個(gè)用戶是否具有權(quán)限myuser.has_perm('foo.can_vote')
默認(rèn)權(quán)限default permissions
如果已經(jīng)在 INSTALLED_APPS配置了django.contrib.auth,它會(huì)保證為installed applications中的每個(gè)Django Model創(chuàng)建3個(gè)缺省權(quán)限:add, change 和 delete。
這些權(quán)限會(huì)在你第一次運(yùn)行 manage.py migrate(1.7之前為syncdb) 時(shí)創(chuàng)建。當(dāng)時(shí)所有的models都會(huì)建立權(quán)限。在這之后創(chuàng)建的新models會(huì)在再次運(yùn)行 manage.py migrate時(shí)創(chuàng)建這些默認(rèn)權(quán)限。這些權(quán)限與admin管理界面中的創(chuàng)建,刪除,修改行為是一一對(duì)應(yīng)的。
假設(shè)你有一個(gè)應(yīng)用 foo ,其中有一個(gè)模型 Bar, 你可以用下述方法來(lái)測(cè)試基本權(quán)限:
add: user.has_perm('foo.add_bar')
change: user.has_perm('foo.change_bar')
delete: user.has_perm('foo.delete_bar')
權(quán)限模型( Permission model)一般不直接使用。
組Groups
組也是作為Model存在的:
@python_2_unicode_compatible class Group(models.Model): """ Groups are a generic way of categorizing users to apply permissions, or some other label, to those users. A user can belong to any number of groups. A user in a group automatically has all the permissions granted to that group. For example, if the group Site editors has the permission can_edit_home_page, any user in that group will have that permission. Beyond permissions, groups are a convenient way to categorize users to apply some label, or extended functionality, to them. For example, you could create a group 'Special users', and you could write code that would do special things to those users -- such as giving them access to a members-only portion of your site, or sending them members-only email messages. """ name = models.CharField(_('name'), max_length=80, unique=True) permissions = models.ManyToManyField(Permission, verbose_name=_('permissions'), blank=True) objects = GroupManager() class Meta: verbose_name = _('group') verbose_name_plural = _('groups') def __str__(self): return self.name def natural_key(self): return (self.name,)
字段fields:
name:必需,80個(gè)字符或更少,例如, 'Awesome Users'。
permissions:ManyToManyField to Permission
group.permissions = [permission_list] group.permissions.add(permission, permission, ...) group.permissions.remove(permission, permission, ...) group.permissions.clear()
Programmatically creating permissions
除了可以使用Model meta來(lái)創(chuàng)建權(quán)限,也可以直接用代碼創(chuàng)建。
例如,為myapp應(yīng)用中的BlogPost模型創(chuàng)建一個(gè)can_publish權(quán)限:
from myapp.models import BlogPost from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType content_type = ContentType.objects.get_for_model(BlogPost) permission = Permission.objects.create(codename='can_publish', name='Can Publish Posts', content_type=content_type)
權(quán)限可以被賦予一個(gè)User對(duì)象通過(guò)它的user_permissions屬性或者賦予一個(gè)Group通過(guò)它的permissions屬性。
權(quán)限緩存
User的權(quán)限檢查時(shí)是可以被緩存的,如果一個(gè)新權(quán)限被賦予一個(gè)User,如果再立即檢查是不會(huì)被檢查出來(lái)的。最簡(jiǎn)單的方法是重新fetch User對(duì)象。
from django.contrib.auth.models import Permission, User from django.shortcuts import get_object_or_404 def user_gains_perms(request, user_id): user = get_object_or_404(User, pk=user_id) #權(quán)限檢查會(huì)緩存現(xiàn)在的權(quán)限集 user.has_perm('myapp.change_bar') permission = Permission.objects.get(codename='change_bar') user.user_permissions.add(permission) # 檢查權(quán)限緩存集 user.has_perm('myapp.change_bar') # False # 請(qǐng)求新實(shí)例 user = get_object_or_404(User, pk=user_id) # Permission cache is repopulated from the database user.has_perm('myapp.change_bar') # True ...
權(quán)限裝飾器
permission_required(perm[, login_url=None, raise_exception=False])
檢查用戶是否具有某個(gè)權(quán)限,類似于@login_required()
from django.contrib.auth.decorators import permission_required @permission_required('polls.can_vote', login_url='/loginpage/') def my_view(request): ...
模板中的權(quán)限
user的的權(quán)限保存在模板變量 {{ perms }}中,是django.contrib.auth.context_processors.PermWrapper實(shí)例。
{{ perms.foo }}
上面的單屬性是User.has_module_perms的代理。如果user擁有foo中的任一權(quán)限,則為True
{{ perms.foo.can_vote }}
上面的兩級(jí)屬性查詢是User.has_perm的代理,如果用戶擁有foo.can_vote權(quán)限則為True。
例如:
{% if perms.foo %}You have permission to do something in the foo app.
{% if perms.foo.can_vote %}You can vote!
{% endif %} {% if perms.foo.can_drive %}You can drive!
{% endif %} {% else %}You don't have permission to do anything in the foo app.
{% endif %}
或者:
{% if 'foo' in perms %} {% if 'foo.can_vote' in perms %}In lookup works, too.
{% endif %} {% endif %}
以上是“Django用戶認(rèn)證系統(tǒng)中組與權(quán)限的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!