我正在使用Django REST框架开发REST API。
我定义了自定义详细路线,如:
from __future__ import absolute_import, division, print_function, unicode_literals
class PermissionsMixin(object):
@detail_route(methods=[u'get', u'post'], url_path='permissions')
def detail_permissions(self, request, pk=None):
...
我也试过['get', 'post']
,但结果是一样的。
并测试:
from __future__ import absolute_import, division, print_function, unicode_literals
class ProjectAPITestCase(APITestCase):
def setUp(self):
super(ProjectAPITestCase, self).setUp()
self.factory = APIRequestFactory()
self.detail_view = self.viewset.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy',
})
self.resource_name = 'project'
self.detail_permissions = lambda pk: reverse('api:{}-permissions'.format(self.resource_name),
kwargs={'pk': pk})
def _detail_permissions(self, pk, data={}, user=None):
request = self.factory.post(self.detail_permissions(pk), data=data, format='json')
if user:
force_authenticate(request, user)
resp = self.detail_view(request, pk=pk)
print(resp.data)
resp.render()
return resp
def test_permissions(self):
resp = self._detail_permissions(1, {}, self.user1)
...
当我运行测试时,print
在呈现响应之前返回:
{u'detail': u'Method "POST" not allowed.'}
我将问题追溯到this line,其中request.method.lower()
为post
且self.http_method_names
为[u'get', u'post', u'put', u'patch', u'delete', u'head', u'options', u'trace']
。
我正在使用Python 2.7.9
我做错了什么?我该如何解决这个问题?
谢谢!
答案 0 :(得分:3)
更改此代码(将post方法添加到代码中)
self.detail_view = self.viewset.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy',
'post': 'create'
})