Skip to main content
 首页 » 编程设计

python之"http method not bound to view"在 drf_yasg 中记录基于类的 View 时

2025年01月19日10insus

之前,我记录了我基于函数的 View ,如下所示:

@swagger_auto_schema( 
    operation_id='ChangePassword', 
    methods=['POST'], 
    request_body=ChangePasswordSerializer, 
    responses={ 
        '200': 'empty response body', 
    }) 
def change_password(request): 
    # code here 

然后我们将 View 切换为基于类的,所以我只是将文档装饰器复制粘贴到 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" 

这是怎么回事?此错误消息是什么意思?

请您参考如下方法:

请注意,在 source core 中的 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 将有效。