未加星标

Django-REST User Level Permissions and Object Level Permissions

字体大小 | |
[开发(python) 所属分类 开发(python) | 发布者 店小二03 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

Let us cosider the scenario of Authors, Books, Readers.

Authors are only allowed to write the books

Readers are only allowed to read the Books.

models.py

from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
class User(AbstractBaseUser, PermissionsMixin):
USER_TYPES = (
("Author", "Author"),
("Reader", "Reader"),
("Publisher", "Publisher")
)
username = models.CharField(max_length=100, unique=True)
first_name = models.CharField(_("first name"), max_length=30, blank=True, null=True)
last_name = models.CharField(_("last name"), max_length=30, blank=True, null=True)
email = models.EmailField(_("email address"), unique=True)
is_staff = models.BooleanField(_("staff status"), default=False)
is_active = models.BooleanField(_("active status"), default=True)
user_type = models.CharField(choices=USER_TYPES)
def __str__(self):
return self.email
class Book(models.Model):
READ_OPTIONS = (
('YES', 'YES'),
('NO', 'NO')
)
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
is_allowed_to_read = models.CharField(choices=READ_OPTIONS)
def __str__(self):
return self.name

permissions.py

from rest_framework.permissions import BasePermission
class IsAllowedToWrite(BasePermission):
def has_permission(self, request, view):
return request.user.user_type == "Author"
class IsAllowedToRead(BasePermission):
def has_object_permission(self, request, view, obj):
return obj.is_allowed_to_read == "YES"

views.py

from rest_framework import generics
from app.permissions import IsAllowedToWrite, IsAllowedToRead
from app.serializers import WriteBookSerializer,
class WriteBookView(generics.CreateAPIView):
serializer_class = WriteBookSerializer
permission_classes = (IsAllowedToWrite,)
class ReadBookView(generics.RetrieveAPIView):
serializer_class = ReadBookSerializer
permission_classes = (IsAllowedToWrite,) for more details visit rest-framework documentaion or source code github

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

主题: RESTDjangoTIOPT
分页:12
转载请注明
本文标题:Django-REST User Level Permissions and Object Level Permissions
本站链接:http://www.codesec.net/view/530669.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(20)