所以这在Django与我决定做一个测试api项目花了一些弄乱。
下面是我的应用程序中的urls.py文件的内容。
urlpatterns = [
url(r'^([0-9]{4})/([0-9]{2})/test/$', views.DuperView.as_view()),
url(r'^test/([0-9]{4})/([0-9]{2})/$', views.SuperView.as_view()),
url(r'^test/', views.TestView.as_view()),
]
起初,我开始搞乱端点测试/添加数据。 uri test/0000/00(第二个)将每个附加组件传递到apiview中作为参数(如下面的view.py代码所示。如果将uri的组件移动到测试/端点仍然会以相同的方式将相同的信息传递给apiview,因此您可以执行/ 0000/00/test /,并且这些组件仍然会传递到我们的api视图。
这是我的views.py文件内容
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
class TestView(APIView):
def get(self, request, format=None):
an_apiview = [
'this',
'is',
'a',
'list',
]
return Response({'http_method': 'GET', 'api_view': an_apiview})
class SuperView(APIView):
# because our url is test/{year}/{month} in the urls.py file
# {year} is passed to the view as the year argument
# {month} is passed to the view as the month argument
def get(self, request, year, month, format=None):
an_apiview = [
'this',
'is',
'a',
'super',
'list',
]
return Response({'http_method': 'GET', 'api_view': an_apiview})
class DuperView(APIView):
# because our url is {year}/{month}/test/ in the urls.py file
# {year} is passed to the view as the year argument
# {month} is passed to the view as the month argument
def get(self, request, year, month, format=None):
an_apiview = [
'this',
'is',
'a',
'duper',
'list',
]
return Response({'http_method': 'GET', 'api_view': an_apiview})
请问这是在views.py还是有一个更优雅的方式来做到这一点?所有的请求将有/公司/位置有没有一种方法可以轻松地添加到每个请求的开始那个API? –
所以我抬头看看Spring,它看起来像y一般来说,你误解了编程语言和框架。据我所知,当我在Google上查看时,我使用python和名为django的框架,Django没有名为@RequestMapping的属性。 –
这你必须在控制器中完成。如果你得到相同的网址模式,你应该可以在课堂上做到这一点。所以你不需要在每种方法中捕获路径变量。我不知道如何在Python中做到这一点。但肯定应该有办法。请参阅[django](https://docs.djangoproject.com/en/1.11/topics/http/urls/) – rnavagamuwa