从父目录导入Flask应用 [英] Flask import app from parent directory

查看:42
本文介绍了从父目录导入Flask应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构如下的应用程序:

I have an app structured like so:

name
    -app.py
    -__init__.py
    -folder1
            -views.py
            -models.py
            -__init__.py

我的app.py的内容:

The content of my app.py:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

if __name__ == '__main__':
    app.run('0.0.0.0')

名称文件夹中的 init .py是:

And init.py in the name folder is:

from app import app

如何将这个应用程序导入views.py?目前,我正在使用

How would I import this app into views.py? Currently, I'm using

from name import app
from models import Class1
app.add_url_rule('/', view_func=Class1.as_view('class1'))

,但是当我运行该应用程序时,它返回404错误.

, but then when I run the app it returns a 404 error.

推荐答案

这是我对我的应用所做的:

This is what I did to my apps:

__ init __.py 中:

from .app import app

with app.app_context():
    from .folder1 import models, views  # noqa

folder1/views.py 中:

from flask import current_app as app
# then use `app` as usual
from .models import Class1
app.add_url_rule('/', view_func=Class1.as_view('class1'))

" app_context()"将当前的 app 对象注入到 current_app 代理中.阅读以了解该机制.

The "app_context()" injects the current app object into the current_app proxy. Read this to understand the mechanism.

建议明确使用相对导入(带有额外的点".").

Also it is recommended to explicitly use relative imports (with the extra dots ".").

这篇关于从父目录导入Flask应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆