python - flask蓝图文件结构

标签 python flask blueprint

我对 flask 蓝图有一些烦恼

我的项目结构:

hw
...run.py
...sigcontoj
......__init__.py
......admin
.........__init__.py
.........views.py
.........models.py
......frontend
.........__init__.py
.........views.py
.........models.py

运行.py:

from sigcontoj import create_app
from sigcontoj.frontend import frontend


app = create_app(__name__)


if __name__ == '__main__':
    print app.url_map
    print app.blueprints
    app.run(debug = True)

sigcontoj__init__.py:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from sigcontoj.frontend import frontend


db = SQLAlchemy()

def create_app(name=__name__):
    app = Flask(name, static_path='/static')
    app.register_blueprint(frontend, url_prefix=None)
    app.secret_key = 'dfsdf1323jlsdjfl'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///soj.db'
    db.init_app(app)
    return app

sigcontoj\frontend__init__.py:

from flask import Blueprint

frontend = Blueprint('frontend', __name__, template_folder='templates')

sigcontoj\frontend\models.py:

from datetime import datetime
from sigcontoj import db


class News(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(256))
    content = db.Column(db.Text)
    publish_time = db.Column(db.DateTime, default=datetime.now())

    def __repr__(self):
        return '<News : %s>' % self.title

sigcontoj\frontend\views.py:

from sigcontoj.frontend.models import News
from sigcontoj.frontend import frontend


@frontend.route('/')
def index():
    news = News.query.all()[0:5]
    return "hello world"

app.url_map 的输出是

Map([' (HEAD, OPTIONS, GET) -> static>])

而且索引页是404。

我的代码有没有错误?

最佳答案

您遇到的问题是,即使您导入了 frontend Blueprint,因为您从未导入 views index (/) 路由从未在 frontend 中注册。如果您更新 sigcontoj/__init__.py 以导入 sigcontoj.frontend.views:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from sigcontoj.frontend import frontend
import sigcontoj.frontend.views

然后一切都应该工作。

关于python - flask蓝图文件结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16099230/

相关文章:

java - 通过 Camel Blueprint 中的属性配置 SQL 数据源(在 Karaf 中)

python - 蓝图和工厂模式一起工作?

我的代码中的 Python 3.1 "Else:"问题

python - 如何在 Matplotlib 中将子图旋转 45 度?

python - 类型错误 : unsupported operand type(s) for +: 'int' and 'str' when trying to 'print'

Python - 将 Flask 应用程序的名称更改为 app.py 时出现 ModuleNotFoundError。可能的解决方案?

python - Flask-login 不重定向到上一页

python - 过滤过去 x 天的 pandas 数据框

docker - 如何在Docker容器中将Flask应用程序 Debug模式设置为True

java - Java Petstore 2.0 蓝图