我有一个Django REST Framework项目,我试图生成Swagger文档。但是,在我的网址文件中,我使用的是路由器,而且与Swagger似乎并不是很好。我按照this discussion中的说明进行操作,这是我得到的:
这非常有效:
router = CustomRouter(
schema_title='My API',
schema_renderers=[renderers.CoreJSONRenderer, OpenAPIRenderer],
trailing_slash=False
)
router.register(r'users', UserViewSet, base_name='user')
router.register(r'foos', FooFieldViewSet)
router.register(r'bars', BarViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^admin/', include(admin.site.urls)),
url(r'^session-auth/', include('rest_framework.urls')),
url(r'^rest-auth/', include('rest_auth.urls')),
]
我得到了预期的页面:
但是,如果我将SwaggerUIRenderer
添加到schema_renderers
列表中,它就不再有效了:
router = CustomRouter(
schema_title='My API',
schema_renderers=[renderers.CoreJSONRenderer, OpenAPIRenderer, SwaggerUIRenderer],
trailing_slash=False
)
# ...
我得到这个页面:
我做错了什么?
更新
如果我添加?format=swagger
,我会:
/home/vagrant/ve/lib/python3.4/importlib/_bootstrap.py:321: RemovedInDjango110Warning: django.core.context_processors is deprecated in favor of django.template.context_processors.
return f(*args, **kwds)
[22/Jul/2016 09:00:10] "GET /?format=swagger HTTP/1.1" 403 3688
Internal Server Error: /
Traceback (most recent call last):
File "/home/vagrant/ve/lib/python3.4/site-packages/django/core/handlers/base.py", line 174, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/vagrant/ve/lib/python3.4/site-packages/django/core/handlers/base.py", line 172, in get_response
response = response.render()
File "/home/vagrant/ve/lib/python3.4/site-packages/django/template/response.py", line 160, in render
self.content = self.rendered_content
File "/home/vagrant/ve/lib/python3.4/site-packages/rest_framework/response.py", line 70, in rendered_content
ret = renderer.render(self.data, media_type, context)
File "/home/vagrant/ve/lib/python3.4/site-packages/rest_framework_swagger/renderers.py", line 18, in render
data = json.loads(codec.dump(data))
File "/home/vagrant/ve/lib/python3.4/site-packages/openapi_codec/__init__.py", line 34, in dump
data = generate_swagger_object(document)
File "/home/vagrant/ve/lib/python3.4/site-packages/openapi_codec/encode.py", line 8, in generate_swagger_object
parsed_url = urlparse.urlparse(document.url)
AttributeError: 'list' object has no attribute 'url'
[22/Jul/2016 09:00:10] "GET /?format=openapi HTTP/1.1" 500 81912
答案 0 :(得分:0)
此时,SwaggerUIRenderer不会覆盖根视图(html)的默认可浏览API,因此您必须指定format
查询参数以在渲染器之间切换。
例如:
http://localhost:8000/?format=swagger
- > Swagger UI界面
http://localhost:8000/?format=openapi
- > Swagger / OpenAPI JSON规范
http://localhost:8000/?format=corejson
- > CoreAPI CoreJSON
对于403,听起来像是身份验证配置,或者您没有登录。
或者,删除路由器的架构属性,而是创建一个返回架构的单独视图。