Blueprint - 中文译为 蓝图。通过它规划 flask 中的各项功能模块。本笔记参考了: https://spacewander.github.io/explore-flask-zh/7-blueprints.html

Flask 项目结构

在项目结构的规划方面参考了 Larger Applications 即采用 package 形式。

/foshime
    /static
    /templates
    /views
        user.py
    __init__.py
    database.py
setup.py

setup.py

from setuptools import setup

setup(
    name='foshime',
    packages=['foshime'],
    include_package_data=True,
    install_requires=[
        'flask',
        'flask-sqlalchemy',
    ]
)

/foshime/init.py

from flask import Flask
from .views import user

app = Flask(__name__)
app.register_blueprint(user.mod)

/foshime/views/user.py

from flask import Blueprint

mod = Blueprint('user', __name__, url_prefix='/user/')

@mod.route('')
def index():
    return 'Hello world!'

/foshime/database.py

from sqlalchemy import create_engine, Column, String, Integer
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:///database.db', convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                        autoflush=False,
                                        bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    Base.metadata.create_all(bind=engine)

class Temple(Base):
    __tablename__ = 'temples'
    id = Column(Integer, primary_key=True)
    name = Column(String(100))
    address = Column(String(200))

    def __init__(self, name=None, address=None):
        self.name = name
        self.address = address
    
    def __repr__(self):
        return '<Name %r>' % (self.name)

运行方法

导入项目名环境变量:

$ export FLASK_APP=foshime

启用 debug 模式:

$ export FLASK_DEBUG=true

安装项目依赖,运行程序:

pip install -e .
flask run