跨flask应用程序重用样板代码

2024-04-27 02:52:39 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的许多flask应用程序中,我都有一些错误处理调用。例如,我的404响应是使用@app.errorhandler修饰符定义的:

@app.errorhandler(404)
def page_not_found(e):
    return jsonify({'status': 'error',
                    'reason': '''There's no API call for %s''' % request.base_url,
                    'code': 404}), 404

因为我有大量的样板代码,所以我想把它放在一个公共文件中,然后从一个地方继承或导入我的flask应用程序。在

是否可以从不同的模块继承或导入flask样板代码?在


Tags: 代码app应用程序flaskreturn定义defstatus
1条回答
网友
1楼 · 发布于 2024-04-27 02:52:39

当然有,但是你需要参数化注册。在

不要使用decorators,而是将注册移到函数:

def page_not_found(e):
    return jsonify({'status': 'error',
                    'reason': '''There's no API call for %s''' % request.base_url,
                    'code': 404}), 404


def register_all(app):
    app.register_error_handler(404, page_not_found)

然后导入register_all,并用Flask()对象调用它。在

它使用^{}函数而不是decorator。在

为了支持蓝图,您还需要等待Flask的下一个版本(其中包括this commit),或者直接使用decorator函数:

^{pr2}$

对于许多这样的任务,您也可以使用蓝图,前提是使用^{}

common_errors = Blueprint('common_errors')


@common_errors.errorhandler(404)    
def page_not_found(e):
    return jsonify({'status': 'error',
                    'reason': '''There's no API call for %s''' % request.base_url,
                    'code': 404}), 404

并不是所有的都可以由蓝图来处理,但是如果您注册的只是错误处理程序,那么蓝图是一种很好的方法。在

像往常一样导入蓝图并将其注册到您的应用程序:

from yourmodule import common_errors
app.register_blueprint(common_errors)

相关问题 更多 >