我们可以在单独的模块中使用Flask错误处理程序

Joh*_*wyn 6 python flask

我们正在将Flask应用程序从基于函数的视图迁移到可插入视图,除了错误处理程序之外,所有这些都按预期工作.我试图将所有错误处理程序放在一个名为error_handlers.py的模块中,并将其导入主模块.但它没有用.尝试在谷歌搜索并按照相同的方式找到一些Git回购,但它不适合我,请帮我解决这个问题.

app
 |
 |__ __init__.py
 |__ routing.py (which has the app=Flask(__name__) and imported error handlers here [import error_handlers])   
 |__ views.py 
 |__ error_handlers.py (Ex: @app.errorhandler(FormDataException)def form_error(error):return jsonify({'error': error.get_message()})
 |__ API (api modules)
      |
      |
      |__ __init__.py
      |__ user.py  
Run Code Online (Sandbox Code Playgroud)

我使用的是Python 2.6和Flask 0.10.1.

fam*_*kin 10

虽然您可以使用一些循环导入来执行此操作,例如:

app.py

import flask

app = flask.Flask(__name__)

import error_handlers
Run Code Online (Sandbox Code Playgroud)

error_handlers.py

from app import app

@app.errorhandler(404)
def handle404(e):
    return '404 handled'
Run Code Online (Sandbox Code Playgroud)

显然,在更复杂的场景中,这可能会变得棘手.

Flask有一种干净而灵活的方式来组合来自多个模块的应用程序,这是一个蓝图概念.要使用a注册错误处理程序,flask.Blueprint您可以使用以下任一方法:

例:

error_handlers.py

import flask

blueprint = flask.Blueprint('error_handlers', __name__)

@blueprint.app_errorhandler(404)
def handle404(e):
    return '404 handled'
Run Code Online (Sandbox Code Playgroud)

app.py

import flask
import error_handlers

app = flask.Flask(__name__)
app.register_blueprint(error_handlers.blueprint)
Run Code Online (Sandbox Code Playgroud)

两种方式都达到了相同,取决​​于哪种方式更适合你.

  • @JohnPrawyn 这正是我所说的棘手循环导入的意思。你从`routing`开始,然后导入`error_handlers`,然后再次导入`routing`。这样,`routing` 模块被多次执行,而在模块执行的哪个点引入导入很重要,从而导致错误,例如 *AssertionError: View function mapping is overwriting an existing endpoint function: user_view* 和需要要格外小心地正确订购所有东西。最后,它是复杂的、不灵活的并且容易出错,这就是为什么我们有蓝图可以提供帮助。 (2认同)

Sye*_*b M 0

我认为你导入error_handlers模块routing.py就像

import error_handlers
Run Code Online (Sandbox Code Playgroud)

最好像下面这样导入routing.py

from error_handlers import *
Run Code Online (Sandbox Code Playgroud)

它可能对你有帮助:-)