[英]How to allow only custom urls in Django rest api?
I'm trying to create a simple api to learn how Django works.我正在尝试创建一个简单的 api 来了解 Django 的工作原理。 I'm using rest_framework.
我正在使用 rest_framework。
First, I have created a model:首先,我创建了一个 model:
class User(models.Model):
username = models.CharField(max_length=20, primary_key=True)
password = models.CharField(max_length=50)
token = models.UUIDField(default=uuid.uuid4, editable=False)
creation_dt = models.DateTimeField(auto_now_add=True)
Then I have created a serializer:然后我创建了一个序列化程序:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'password', 'token', 'creation_dt')
read_only_fields = ('creation_dt', 'token',)
And then, in api.py, this code:然后,在 api.py 中,这段代码:
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
permission_classes = [permissions.AllowAny]
serializer_class = UserSerializer
http_method_names = ['get', 'post']
@action(methods=['POST'], detail=False, permission_classes=[permissions.AllowAny], url_path='get_all_users')
def get_all_users(self, request, pk=None):
...
return Response(UserSerializer(self.queryset[:user_number],
As you can see, I added a custom url_path " get_all_users ".如您所见,我添加了自定义 url_path“ get_all_users ”。
So, everything works until here.所以,一切正常,直到这里。 My problem is that I can still access "/users/", "/users/user_name", POST users etc, the normal CRUD app.
我的问题是我仍然可以访问“/users/”、“/users/user_name”、POST 用户等普通的 CRUD 应用程序。
The question is, how can I allow only the url I have especifially created and block all the rest created automatically?问题是,我怎样才能只允许我特别创建的 url 并阻止所有自动创建的 rest?
Thanks.谢谢。
To allow only custom multiple actions in a Django REST framework ModelViewset and disable the default URLs, you can override the get_urls method and remove the default URLs.要在 Django REST 框架 ModelViewset 中仅允许自定义多个操作并禁用默认 URL,您可以覆盖 get_urls 方法并删除默认 URL。
Here is an example of how to do this:以下是如何执行此操作的示例:
class MyModelViewSet(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
def get_urls(self):
# Remove the default URLs
urls = []
# Add custom URLs for multiple actions
url_patterns = [
url(r'^mymodel/custom-action/$', self.custom_action, name='custom-action'),
url(r'^mymodel/another-custom-action/$', self.another_custom_action, name='another-custom-action'),
]
# Return the custom URLs
return url_patterns
@action(detail=False, methods=['post'])
def custom_action(self, request):
# Custom action logic here
pass
@action(detail=False, methods=['post'])
def another_custom_action(self, request):
# Another custom action logic here
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.