Django REST framework -- Authentication & Permissions

互联网 2021/10/12 23:45:30

Authentication & Permissions https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/ 对于view需要限制用户的访问权限, 例如认证 和 许可。Currently our API doesnt have any restrictions on who can edit or delete code snippets…

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.

 

随时随地学软件编程-关注百度小程序和微信小程序
关于找一找教程网

本站文章仅代表作者观点,不代表本站立场,所有文章非营利性免费分享。
本站提供了软件编程、网站开发技术、服务器运维、人工智能等等IT技术文章,希望广大程序员努力学习,让我们用科技改变世界。
[Django REST framework -- Authentication & Permissions]http://www.zyiz.net/tech/detail-240613.html

上一篇:今日头条Go建千亿级微服务的实践

下一篇:巧用 maxTimeMS 服务端超时,避免承载亿级用户的腾讯云数据库MongoDB服务雪崩

赞(0)
关注微信小程序
程序员编程王-随时随地学编程

扫描二维码或查找【程序员编程王】

可以随时随地学编程啦!

技术文章导航 更多>
扫一扫关注最新编程教程