gpt4 book ai didi

django-rest-framework - 将 Django Rest Framework 的可浏览 API 与 APIViews 一起使用?

转载 作者:行者123 更新时间:2023-12-03 07:40:16 25 4
gpt4 key购买 nike

如果我有这样的观点:

class MyAPIView(APIView):
def get(self, request, name=None):
return {"hello": name or "world"}

如何将其包含在生成的文档中?具体来说,如何将其包含在 API 根目录中,以便在访问“http://example.com/api/”时出现?

documentation includes an example带有描述的 APIView,但没有描述实际将其包含在 API 浏览器中的过程。

最佳答案

为了与路由器和 APIView 类或方法混合,使 API 根在 APIRoot View 中显示最少的代码 View ,我编写了一个自定义路由器,它扩展了 DefaultRouter 并覆盖 get_urls 和 get_api_root_view;它看起来如下:

from rest_framework import routers, views, reverse, response

class HybridRouter(routers.DefaultRouter):
def __init__(self, *args, **kwargs):
super(HybridRouter, self).__init__(*args, **kwargs)
self._api_view_urls = {}

def add_api_view(self, name, url):
self._api_view_urls[name] = url

def remove_api_view(self, name):
del self._api_view_urls[name]

@property
def api_view_urls(self):
ret = {}
ret.update(self._api_view_urls)
return ret

def get_urls(self):
urls = super(HybridRouter, self).get_urls()
for api_view_key in self._api_view_urls.keys():
urls.append(self._api_view_urls[api_view_key])
return urls

def get_api_root_view(self):
# Copy the following block from Default Router
api_root_dict = {}
list_name = self.routes[0].name
for prefix, viewset, basename in self.registry:
api_root_dict[prefix] = list_name.format(basename=basename)
api_view_urls = self._api_view_urls

class APIRoot(views.APIView):
_ignore_model_permissions = True

def get(self, request, format=None):
ret = {}
for key, url_name in api_root_dict.items():
ret[key] = reverse.reverse(url_name, request=request, format=format)
# In addition to what had been added, now add the APIView urls
for api_view_key in api_view_urls.keys():
ret[api_view_key] = reverse.reverse(api_view_urls[api_view_key].name, request=request, format=format)
return response.Response(ret)

return APIRoot.as_view()

然后我用它作为 -

router = routers.HybridRouter()
router.register(r'abc', views.ABCViewSet)
router.add_api_view("api-view", url(r'^aview/$', views.AView.as_view(), name='aview-name'))
urlpatterns = patterns('',
url(r'^api/', include(router.urls)),

关于django-rest-framework - 将 Django Rest Framework 的可浏览 API 与 APIViews 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18817988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com