发生了django_rest_framwork" TypeError:' Link'对象不支持项目分配"

时间:2017-05-04 09:14:36

标签: python django django-rest-framework django-swagger

使用Django,DRF,swagger的项目。

下面的url配置:

schema_view = get_swagger_view(title='Pastebin API')
urlpatterns = [
    url(r'^$', schema_view),
    url(r'store', include('store.urls')),
    ... # other urls using routers.SimplerRouter
]

和store / urls.py:

router = routers.SimpleRouter()
router.register(r'', views.StoreViewSet)
urlpatterns = router.urls

和views.StoreViewSet:

class StoreViewSet(BaseObject, GenericViewSet):
    permition_class = ()

    @list_route()
    def detail(self, request):
        return {}

    @list_route(url_path='detail/export')
    def detail_export(self, request):
        return {}

python manage.py runserver之后,访问http://127.0.0.1:8000/#并发生TypeError:

File "/usr/local/share/.virtualenvs/dev-finance/lib/python2.7/site-packages/rest_framework_swagger/views.py", line 32, in get
schema = generator.get_schema(request=request)
File "/usr/local/share/.virtualenvs/dev-finance/lib/python2.7/site-packages/rest_framework/schemas.py", line 242, in get_schema
links = self.get_links(request)
File "/usr/local/share/.virtualenvs/dev-finance/lib/python2.7/site-packages/rest_framework/schemas.py", line 276, in get_links
insert_into(links, keys, link)
File "/usr/local/share/.virtualenvs/dev-finance/lib/python2.7/site-packages/rest_framework/schemas.py", line 79, in insert_into
target[keys[-1]] = value
TypeError: 'Link' object does not support item assignment
[ERROR] 2017-05-04 15:25:06,936 log_message(basehttp.py:131) "GET / HTTP/1.1" 500 20384

错误消息显示,Link对象无法分配值,就像dict一样。

如果我将方法名称从detail_export重命名为details_export,一切都会再次正常。

当rest_framework @list_route装饰时,猜测错误发生了  将方法的网址传输到链接对象。

为什么其他方法会好起来? 我怎么解决这个问题?

2 个答案:

答案 0 :(得分:2)

这是the bug in DRF。可能会在3.6.4中修复。现在你可以:

  1. module.exports = () => ({ "customer/:customerId":"customer?id=:customerId" }); 删除url_path

    list_route
  2. 或使用自定义class StoreViewSet(BaseObject, GenericViewSet): permition_class = () @list_route() def detail(self, request): return {} @list_route() def detail_export(self, request): return {} 自定义SchemaView

    SchemaGenerator

答案 1 :(得分:1)

这是一个黑客:

  1. 打开 您的环境文件夹/ lib目录/ python3.5 /站点包/ rest_framework / schemas.py
  2. 查找“insert_into”功能
  3. 替换它:

    target[keys[-1]] = value
    
  4. 用这个:

    if type(target) != coreapi.Link:
        target[keys[-1]] = value