其他分享
首页 > 其他分享> > Django REST framework -- Authentication & Permissions

Django REST framework -- Authentication & 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