2017-06-16 56 views
0

所以我对django有一个非常基本的理解。我知道我可以在我的urlpatterns中使用像下面这样的字符串来创建一个类似于example.com/test/2005/03的url。创建其中的变量的网址

url(r'^test/([0-9]{4})/([0-9]{2})/$', views.SuperView.as_view()), 

但是如果我想在uri的测试参数之前添加一些东西呢?对于拥有多个位置的企业,是否可以制作一个像这样的网址?

www.example.com/company_name/location_name/test/2005/01 

我想学习如何建立一个灵活的服务,可以为多个公司工作,我想指定的公司,其位置是通过URI的COMPANY_NAME/LOCATION_NAME /段访问数据。在请求中,我想获取这些变量并使用它们在视图和模型中对我的数据库执行连接查询。

回答

0

基本上你可以使用路径变量来做到这一点。如果我正确理解你的问题,你可以在控制器中使用一些URL模式。一个简单的春天的例子将是

@RequestMapping(value = "/{company}/{location}/employees", method =RequestMethod.GET) 
public String test(@PathVariable("company") String company, @PathVariable("location") String location) { 
      //your code 
} 
+0

请问这是在views.py还是有一个更优雅的方式来做到这一点?所有的请求将有/公司/位置有没有一种方法可以轻松地添加到每个请求的开始那个API? –

+0

所以我抬头看看Spring,它看起来像y一般来说,你误解了编程语言和框架。据我所知,当我在Google上查看时,我使用python和名为django的框架,Django没有名为@RequestMapping的属性。 –

+0

这你必须在控制器中完成。如果你得到相同的网址模式,你应该可以在课堂上做到这一点。所以你不需要在每种方法中捕获路径变量。我不知道如何在Python中做到这一点。但肯定应该有办法。请参阅[django](https://docs.djangoproject.com/en/1.11/topics/http/urls/) – rnavagamuwa

0

所以这在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})