Django REST framework -- Authentication & Permissions
2021/10/12 23:45:30
本文主要是介绍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 inserializers.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
andSnippetDetail
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, unlessuser.is_staff
isTrue
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
orOPTIONS
.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 usingPOST
,PUT
, andDELETE
.
这篇关于Django REST framework -- Authentication & Permissions的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-15SendGrid 的 Go 客户端库怎么实现同时向多个邮箱发送邮件?-icode9专业技术文章分享
- 2024-11-15SendGrid 的 Go 客户端库怎么设置header 和 标签tag 呢?-icode9专业技术文章分享
- 2024-11-12Cargo deny安装指路
- 2024-11-02MongoDB项目实战:从入门到初级应用
- 2024-11-01随时随地一键转录,Google Cloud 新模型 Chirp 2 让语音识别更上一层楼
- 2024-10-25Google Cloud动手实验详解:如何在Cloud Run上开发无服务器应用
- 2024-10-24AI ?先驱齐聚 BAAI 2024,发布大规模语言、多模态、具身、生物计算以及 FlagOpen 2.0 等 AI 模型创新成果。
- 2024-10-20goland工具下,如修改一个项目的标准库SDK的版本-icode9专业技术文章分享
- 2024-10-17Go学习:初学者的简单教程
- 2024-10-17Go学习:新手入门完全指南