我需要在一个类中的django rest框架中创建两个GET端点 这是端点将通过api
与另一个系统一起使用我试过
class MyApiView(APIView):
permission_classes = [AllowAny]
def get(self, request):
return Response({'test':'test'})
@list_route(methods=['GET'], )
def two_endpoint(self, request):
return Response({'test': 'test'})
但这不起作用 提前谢谢
答案 0 :(得分:1)
尝试使用ModelViewset class,
的 views.py 强>
撞击>
from rest_framework import viewsets
class MyApiView(viewsets.ModelViewSet):
permission_classes = (AllowAny,)
serializer_class = MySerializer
queryset = Sample.objects.all()
def function_name_1(self, request):
# do stuff
return Response(data="return your data")
def function_name_2(self, request):
# do stuff
return Response(data="return your data")
def function_name_3(self, request, pk):
# do stuff
return Response(data="return your data")
击> <击> 撞击>
的 urls.py 强>
from rest_framework.routers import DefaultRouter
from django.conf.urls import url
router = DefaultRouter()
router.register(r'myendpoint', MyApiView)
urlpatterns = [
url(r'^myendpoint/end_point_1/$', MyApiView.as_view({'get': 'function_name_1'}), name='function_name_1'),
url(r'^myendpoint/end_point_2/$', MyApiView.as_view({'post': 'function_name_2'}), name='function_name_2'),
url(r'^myendpoint/end_point_3/$', MyApiView.as_view({'put': 'function_name_3'}), name='function_name_3'),
]+router.urls
的 UPDATE-1 强>
将您的views.py
更改为此,
from rest_framework import viewsets
class MyApiView(viewsets.ViewSet):
permission_classes = (AllowAny,)
def function_name_1(self, request):
# do stuff
return Response(data="return your data")
def function_name_2(self, request):
# do stuff
return Response(data="return your data")
def function_name_3(self, request):
# do stuff
return Response(data="return your data")