[英]How do I connect modules in python?
Starting to do some more advanced processes in flask and I'm having a hard time figuring out how to import my error handling file.开始在 flask 中做一些更高级的过程,我很难弄清楚如何导入我的错误处理文件。 Code snipets from init and errors.
来自 init 和错误的代码片段。 What's wrong?
怎么了?
I cant get the errors module to load.我无法加载错误模块。 I've tried doing from errors import *, I get an import error, tried moving it out of the factory still get errors.
我试过从错误导入 *,我得到一个导入错误,尝试将它移出工厂仍然得到错误。 Tried from errors import *, tried import errors.
尝试从错误导入 *,尝试导入错误。 All fail to some degree.
都在某种程度上失败了。 Seems to me I'm missing something simple as a comma or something.
在我看来,我缺少一些简单的东西,例如逗号或其他东西。
here's some code这是一些代码
first file - init第一个文件 - 初始化
from flask import Flask, render_template
def create_app():
# Instantiate App
app = Flask(__name__)
with app.app_context():
# Import Blueprints
from .foodtracker.routes import foodtracker
from .fitness.routes import fitness
from .bio.routes import bio
from .home.routes import home
# Import models, and error handler
from . import errors
# Register Blue Prints
app.register_blueprint(foodtracker)
app.register_blueprint(fitness)
app.register_blueprint(bio)
app.register_blueprint(home)
return app
and errors.py和errors.py
from flask import render_template
from . import app
@app.errorhandler(404)
def pagenotfound(error):
return render_template('/errors/404.html'), 404
directory structure目录结构
/fitlife
/fitlife
/bio
/home
/fitness
/foodtracker
__init__.py
errors.py
models.py
You have circular imports.你有循环进口。 Meaning, the
app
file tries to import the errors
file and the errors
file tries to import the app
file.意思是,
app
文件尝试导入errors
文件, errors
文件尝试导入app
文件。 The correct way to handle this would be to 'dumb down' the errors.py
file, meaning making it only contain the errors themselves without using the decorator to register them.处理此问题的正确方法是“简化”
errors.py
文件,这意味着使其仅包含错误本身,而不使用装饰器来注册它们。 Then, the errors.py
file will not need to import app
.然后,
errors.py
文件将不需要导入app
。 The registration can be done using app.register_error_handler
from the higher-level file, instead.可以使用更高级别文件中的
app.register_error_handler
来完成注册。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.