Skip to content

Commit 095f896

Browse files
committed
Python: Add examples of class/function based views
1 parent 9bbf08d commit 095f896

File tree

2 files changed

+29
-6
lines changed
  • python/ql/test/library-tests/frameworks/rest_framework/testapp

2 files changed

+29
-6
lines changed

python/ql/test/library-tests/frameworks/rest_framework/testapp/urls.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,6 @@
1111
urlpatterns = [
1212
path("", include(router.urls)),
1313
path("api-auth/", include("rest_framework.urls", namespace="rest_framework")),
14-
path("example/", views.example), # $routeSetup="example/"
14+
path("class-based-view/", views.MyClass.as_view()), # $routeSetup="lcass-based-view/"
15+
path("function-based-view/", views.function_based_view), # $routeSetup="function-based-view/"
1516
]

python/ql/test/library-tests/frameworks/rest_framework/testapp/views.py

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,13 @@
22
from .serializers import FooSerializer, BarSerializer
33

44
from rest_framework import viewsets
5+
from rest_framework.decorators import api_view
6+
from rest_framework.views import APIView
7+
from rest_framework.request import Request
8+
from rest_framework.response import Response
59

6-
10+
# Viewsets
11+
# see https://www.django-rest-framework.org/tutorial/quickstart/
712
class FooViewSet(viewsets.ModelViewSet):
813
queryset = Foo.objects.all()
914
serializer_class = FooSerializer
@@ -13,8 +18,25 @@ class BarViewSet(viewsets.ModelViewSet):
1318
queryset = Bar.objects.all()
1419
serializer_class = BarSerializer
1520

21+
# class based view
22+
# see https://www.django-rest-framework.org/api-guide/views/#class-based-views
23+
24+
class MyClass(APIView):
25+
def initial(self, request, *args, **kwargs):
26+
# this method will be called before processing any request
27+
super().initial(request, *args, **kwargs)
28+
29+
def get(self, request):
30+
return Response("GET request")
31+
32+
def post(self, request):
33+
return Response("POST request")
34+
35+
36+
# function based view
37+
# see https://www.django-rest-framework.org/api-guide/views/#function-based-views
38+
1639

17-
# this is pure django
18-
from django.http import HttpResponse, HttpRequest
19-
def example(request: HttpRequest):
20-
return HttpResponse("example")
40+
@api_view(["GET", "POST"])
41+
def function_based_view(request: Request):
42+
return Response({"message": "Hello, world!"})

0 commit comments

Comments
 (0)