在Django RestFramework中,如何更改Api Root文档?

时间:2013-07-05 20:13:21

标签: django django-rest-framework docstring

在django RestFramework中,是否有任何“官方”方式为“Api Root”生成文档?

在查看RestFramework的源代码之后,我通过继承DefaultRouter找到了解决方法:

from rest_framework import routers

class MyRouter(routers.DefaultRouter):
    def get_api_root_view(self):
        api_root_view = super(MyRouter, self).get_api_root_view()
        ApiRootClass = api_root_view.cls

        class MyAPIRoot(ApiRootClass):
            """My API Root documentation"""
            pass

        return MyAPIRoot.as_view()

router = MyRouter()

是否有更清洁或更好的方法?

6 个答案:

答案 0 :(得分:11)

我通过实验找到了解决方案。

我更喜欢这个线程中的其他解决方案,因为它需要更少的代码,并允许您自定义API标题,以及API根目录的文档。

from rest_framework import routers

class ThisWillBeTheApiTitleView(routers.APIRootView):
    """
    This appears where the docstring goes!
    """
    pass


class DocumentedRouter(routers.DefaultRouter):
    APIRootView = ThisWillBeTheApiTitleView


router = DocumentedRouter()
router.register(r'items', ItemsViewSet)

这将呈现如下:

Demonstration

答案 1 :(得分:10)

我是新手,但我发现您可以使用SimpleRouter代替DefaultRouter来指定自己的APIRoot

在你的api模块的urls.py

from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
router = SimpleRouter()

urlpatterns = patterns('api.views',
    url(r'^$', views.APIRoot.as_view()),
    url(r'', include(router.urls)),
)

然后在课堂评论中指定文档

from rest_framework import generics

class APIRoot(generics.GenericAPIView):
    """
    My API documentation
    """

答案 2 :(得分:4)

很难覆盖APIRoot类。实现所需内容的最简单方法可能是在__doc__中在运行时修改APIRootClass的urls.py属性:

class Router(routers.DefaultRouter):
    def get_api_root_view(self, api_urls=None):
        root_view = super(Router, self).get_api_root_view(api_urls=api_urls)
        root_view.cls.__doc__ = "Place your documentation here"
        return root_view

router = Router()
router.register(...)

urlpatterns = [
    url(r'^', include(router.urls)),
]

答案 3 :(得分:2)

如果有人想要内联样式

   router = DefaultRouter()

   router.get_api_root_view().cls.__name__ = "Root API name"
   router.get_api_root_view().cls.__doc__ = "Your Description"

答案 4 :(得分:0)

@api_view(['GET'])
def api_root(request, format=None):
    return Response({
        'users': reverse('user-list', request=request, format=format),
        'snippets': reverse('snippet-list', request=request, format=format)
    })

答案 5 :(得分:0)

由于上面的frost-nzcr4's comment,我找到了一种不错的方法:


from rest_framework import routers
from django.utils.safestring import mark_safe


class MyAPIRootView(routers.APIRootView):
    """
    Controls appearance of the API root view
    """

    def get_view_name(self) -> str:
        return "My API"

    def get_view_description(self, html=False) -> str:
        text = "My REST API"
        if html:
            return mark_safe(f"<p>{text}</p>")
        else:
            return text


class MyRouter(routers.DefaultRouter):
    APIRootView = MyAPIRootView

然后在您的urls.py中使用此路由器:

router = MyRouter()