"http method not bound to view" 在 drf_yasg 中记录基于 class 的视图时
"http method not bound to view" when documenting class-based view in drf_yasg
之前,我记录了我基于函数的视图,如下所示:
@swagger_auto_schema(
operation_id='ChangePassword',
methods=['POST'],
request_body=ChangePasswordSerializer,
responses={
'200': 'empty response body',
})
def change_password(request):
# code here
然后我们将视图切换为基于 class,所以我只是将文档装饰器复制粘贴到 post
方法:
class UserChangePasswordView(APIView):
@swagger_auto_schema(
operation_id='ChangePassword',
methods=['POST'],
request_body=ChangePasswordSerializer,
responses={
'200': 'empty response body',
})
def post(self, request):
# code here
但是,在 运行 这个装饰器上,drf_yasg
抛出了异常
File "/usr/local/lib/python3.6/site-packages/drf_yasg/utils.py", line 126, in decorator
assert all(mth in available_methods for mth in _methods), "http method not bound to view"
这是怎么回事?此错误消息是什么意思?
事实证明,在装饰器中指定视图的 HTTP 方法以及通过应用装饰器的方法的名称隐式指定是无效的。
解决方案是简单地从装饰器中删除 methods
键:
class UserChangePasswordView(APIView):
@swagger_auto_schema(
operation_id='ChangePassword',
request_body=ChangePasswordSerializer,
responses={
'200': 'empty response body',
})
def post(self, request):
# code here
请注意 source core of drf-yasg
中提到了
method
and methods
are mutually exclusive and must only be present when decorating a view method that more than one HTTP request method.
因此,如果您的 UserChangePasswordView.post()
处理了不止一种方法,methods
将有效。
之前,我记录了我基于函数的视图,如下所示:
@swagger_auto_schema(
operation_id='ChangePassword',
methods=['POST'],
request_body=ChangePasswordSerializer,
responses={
'200': 'empty response body',
})
def change_password(request):
# code here
然后我们将视图切换为基于 class,所以我只是将文档装饰器复制粘贴到 post
方法:
class UserChangePasswordView(APIView):
@swagger_auto_schema(
operation_id='ChangePassword',
methods=['POST'],
request_body=ChangePasswordSerializer,
responses={
'200': 'empty response body',
})
def post(self, request):
# code here
但是,在 运行 这个装饰器上,drf_yasg
抛出了异常
File "/usr/local/lib/python3.6/site-packages/drf_yasg/utils.py", line 126, in decorator
assert all(mth in available_methods for mth in _methods), "http method not bound to view"
这是怎么回事?此错误消息是什么意思?
事实证明,在装饰器中指定视图的 HTTP 方法以及通过应用装饰器的方法的名称隐式指定是无效的。
解决方案是简单地从装饰器中删除 methods
键:
class UserChangePasswordView(APIView):
@swagger_auto_schema(
operation_id='ChangePassword',
request_body=ChangePasswordSerializer,
responses={
'200': 'empty response body',
})
def post(self, request):
# code here
请注意 source core of drf-yasg
中提到了
method
andmethods
are mutually exclusive and must only be present when decorating a view method that more than one HTTP request method.
因此,如果您的 UserChangePasswordView.post()
处理了不止一种方法,methods
将有效。