ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Django REST framework -- Authentication & Permissions

2021-10-12 23:33:08  阅读:282  来源: 互联网

标签:permission -- self REST Django framework class snippets permissions


Authentication & Permissions

https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/

对于view需要限制用户的访问权限, 例如认证 和 许可。

Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that:

  • Code snippets are always associated with a creator.
  • Only authenticated users may create snippets.
  • Only the creator of a snippet may update or delete it.
  • Unauthenticated requests should have full read-only access.

 

Adding information to our model

https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#adding-information-to-our-model

在snippet模型中,添加 owner 和 highlighted field。

owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE)
highlighted = models.TextField()

 

引入 高亮代码 工具

from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
from pygments import highlight

 

在创建snippet 序列化类中, 添加save函数, 保存高亮后的结果。

def save(self, *args, **kwargs):
    """
    Use the `pygments` library to create a highlighted HTML
    representation of the code snippet.
    """
    lexer = get_lexer_by_name(self.language)
    linenos = 'table' if self.linenos else False
    options = {'title': self.title} if self.title else {}
    formatter = HtmlFormatter(style=self.style, linenos=linenos,
                              full=True, **options)
    self.highlighted = highlight(self.code, lexer, formatter)
    super(Snippet, self).save(*args, **kwargs)

 

Adding endpoints for our User models

https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#adding-endpoints-for-our-user-models

在用户的序列化类中, 添加此用户对应的所有 snippets的主键field。

from django.contrib.auth.models import User

class UserSerializer(serializers.ModelSerializer):
    snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())

    class Meta:
        model = User
        fields = ['id', 'username', 'snippets']

 

用户的view定义

from django.contrib.auth.models import User


class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer


class UserDetail(generics.RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

 

Associating Snippets with Users

https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#associating-snippets-with-users

SnippetList视图中, 在创建函数中, 将当前用户保存为 owner字段。

def perform_create(self, serializer):
    serializer.save(owner=self.request.user)

 

Updating our serializer

https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#adding-required-permissions-to-views

SnippetSerializer中,添加owner为只读声明。

Now that snippets are associated with the user that created them, let's update our SnippetSerializer to reflect that. Add the following field to the serializer definition in serializers.py:

owner = serializers.ReadOnlyField(source='owner.username')

 

Adding required permissions to views

https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#adding-required-permissions-to-views

在视图中 ,添加许可声明。

Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.

REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is IsAuthenticatedOrReadOnly, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.

First add the following import in the views module

 

from rest_framework import permissions

 

Then, add the following property to both the SnippetList and SnippetDetail view classes.

permission_classes = [permissions.IsAuthenticatedOrReadOnly]

 

permissions

https://www.django-rest-framework.org/api-guide/permissions/#api-reference

AllowAny

The AllowAny permission class will allow unrestricted access, regardless of if the request was authenticated or unauthenticated.

This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.

IsAuthenticated

The IsAuthenticated permission class will deny permission to any unauthenticated user, and allow permission otherwise.

This permission is suitable if you want your API to only be accessible to registered users.

IsAdminUser

The IsAdminUser permission class will deny permission to any user, unless user.is_staff is True in which case permission will be allowed.

This permission is suitable if you want your API to only be accessible to a subset of trusted administrators.

IsAuthenticatedOrReadOnly

The IsAuthenticatedOrReadOnly will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; GET, HEAD or OPTIONS.

This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.

 

 

The Browsable API

https://www.django-rest-framework.org/topics/browsable-api/#urls

https://www.geeksforgeeks.org/?p=563823

 

API may stand for Application Programming Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the HTML format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using POST, PUT, and DELETE.

 

标签:permission,--,self,REST,Django,framework,class,snippets,permissions
来源: https://www.cnblogs.com/lightsong/p/15400098.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有