如何导入与所在文件同名的蓝图?

How to import blueprints with the same name as the file they are in?

背景

我正在尝试设置一个蓝图,其名称与其所在的文件名相匹配,这样当我在 app.py 中引用它时,我就知道蓝图的来源。这应该是可能的,因为 exploreflask 上的示例使用相同的模式。尽管如此,我仍然无法弄清楚如何使用我的结构进行这项工作。

文件结构

├── app.py
├── frontend
    ├── __init__.py
    └── views
        ├── home.py
        └── __init__.py

例子

frontend/views/home.py

from flask import Blueprint, render_template

home = Blueprint('home', __name__)
home1 = Blueprint('home1', __name__)

frontend/views/__init__.py

from .home import home
from .home import home1

app.py

from flask import Flask

from frontend.views import home
from frontend.views import home1

print (type(home))  --> <class 'function'> 
print (type(home1)) --> <class 'flask.blueprints.Blueprint'>

As home1 正确注册为 Blueprinthome 没有 我怀疑 有名称冲突,但我不知道如何解决,尽管调查 this excellent article 关于导入约定。

因此,当我尝试在该应用程序中注册我的蓝图时 这将起作用:

app.register_blueprint(home1, url_prefix='/home1') --> Fine

但这不会:

app.register_blueprint(home, url_prefix='/home')
--> AttributeError: 'function' object has no attribute 'name'

为什么不继续使用 home1?

  1. 我想了解如何解决冲突
  2. 我希望能够使用与它们所在的文件名相同的路由名称,如下所示:

frontend/views/home.py

from flask import Blueprint, render_template

home = Blueprint('home', __name__)

@home.route('/')
def home():
  pass

尽量在蓝图模块中使用大写字母。

您也可以使用模块中的 url_prefix。

Home = Blueprint("Home", __name__, url_prefix="/home")

@Home.route("/")
def home():
    pass

我认为您的 views/__init__.py 文件导致了这个问题。它使 python 假设您的 home.py 文件是要导入的模块。我相信 from frontend.views import home 行试图导入 home.py 文件而不是你想要的 home.home 蓝图。

这是一个工作示例:

/app.py

from app import create_app
app = create_app()

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

/app/__init__.py

from flask import Flask

def create_app():
    app = Flask(__name__) 
    from .bp import bp  
    app.register_blueprint(bp)   
    return app

/app/bp/__init__.py

from flask import Blueprint
bp = Blueprint('bp', __name__, template_folder='templates')
from . import views

/app/bp/views.py

from app.bp import bp

@bp.route('/helloworld')
def helloworld():

    return "hello world"