[英]What do I need to do to a function in views.py works?
我正在开发一个 API,我需要创建一个函数,在不到 10 分钟的时间内不允许使用相同的帖子格式,但是如果用户使用“GET”请求,我只是想在终端中打印一些内容方法,但它不起作用。
网址.py:
from django.urls import include, path
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'products',views.ProductsViewSet)
router.register(r'product-images',views.ProductImagesViewSet)
#router.register(r'^products/', views.testIt, basename="TestIt")
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
path('products/', views.testIt, name = "testIt"),
]
视图.py:
from rest_framework import viewsets
from .serializers import ProductsSerializers
from .serializers import ProductImagesSerializers
from .models import Products
from .models import ProductImages
from rest_framework import status
from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.http import JsonResponse
class ProductsViewSet(viewsets.ModelViewSet, APIView):
queryset = Products.objects.all().order_by('id')
serializer_class = ProductsSerializers
def testIt(self, request, pk=None):
if request.method == 'GET':
print('Testando')
return Response('Teste!', status = status.HTTP_400_NOT_FOUND)
class ProductImagesViewSet(viewsets.ModelViewSet):
queryset = ProductImages.objects.all().order_by('id')
serializer_class = ProductImagesSerializers
我仍然看到数据,但是当我使用 get 方法时它没有返回任何消息或打印任何内容。 先感谢您!!
您传递给函数的第一个参数是self
,将其删除。 否则, Request
对象将在该变量中而不是request
,它与您在if
语句中一起工作。
另外,用api_view
装饰函数:https : api_view
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.