You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为导入的函数应用带参数的装饰器(Flask-RESTX场景)

问题描述

需要给导入的函数应用带参数的装饰器,原代码中错误处理函数handle_bad_requests写在当前文件,现在希望将其移至exceptions模块中,但尝试的写法报错参数过多。

原可运行代码:

from flask_restx import Namespace
from . import exceptions as e

api = Namespace('v2', 'API Version 2' )

@api.errorhandler(e.MissingPrompt)
def handle_bad_requests(error):
    '''Namespace error handler'''
    logger.warning(error.log)
    return({'message': error.specific}, error.code)

期望实现的结构(处理函数移至exceptions模块):

from flask_restx import Namespace
from . import exceptions as e

api = Namespace('v2', 'API Version 2' )

@api.errorhandler(e.MissingPrompt)
e.handle_bad_requests # 此处写法不正确

之前尝试的错误写法:

handle_bad_requests  = api.errorhandler(e.handle_bad_requests, e.MissingPrompt)

该写法报错“传入参数过多”。

解决方案

带参数的装饰器api.errorhandler(e.MissingPrompt)的执行逻辑是:先传入异常类e.MissingPrompt,返回一个真正用于装饰函数的装饰器,再将处理函数传入这个返回的装饰器。

正确的写法直接展开装饰器语法糖即可:

from flask_restx import Namespace
from . import exceptions as e

api = Namespace('v2', 'API Version 2')

# 先调用带参数的装饰器获取装饰函数,再传入导入的处理函数
api.errorhandler(e.MissingPrompt)(e.handle_bad_requests)

错误原因说明

之前的错误写法是把处理函数和异常类同时传给了api.errorhandler,但api.errorhandler仅接受异常类作为参数,它的作用是生成适配该异常的装饰器,而非直接处理函数。因此传入两个参数会触发“参数过多”的报错。

内容的提问来源于stack exchange,提问作者Db0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 17:30:31