在线问答系统–蓝图
Blueprint 是一种组织一组相关视图及其他代码的方式。与把视图及其他 代码直接注册到应用的方式不同,蓝图方式是把它们注册到蓝图,然后在工厂函数中 把蓝图注册到应用。
1. 蓝图的实现方法
蓝图我们可以根据功能或者模块来进行划分,项目我们按照模块来进行划分
-
- 按模块划分
- 按模块划分
-
- 按功能划分
在线问题系统一共可以划分成功两个个模块:一个是用户模块(accounts),一个是问题模块(qa)
- 按功能划分
2. 最新目录划分
qa-online
├── app.py
├── conf.py
├── model.py
├── templates
│ ├── accounts
│ │ ├── __init__.py
│ │ ├── templates
│ │ │ ├── login.html
│ │ │ ├── register.html
│ │ │ └── mine.html
│ │ └── view.py
│ ├── qa
│ │ ├── __init__.py
│ │ ├── templates
│ │ │ ├── detail.html
│ │ │ ├── follow.html
│ │ │ ├── index.html
│ │ │ └── write.html
│ │ └── view.py
├── static
│ └── assets
├── utils
│ ├── __init__.py
│ └── contstants.py
└── README.md
2. 蓝图实现
1. 按模块插分
- 配置模块:conf.py
我们连接数据的配置移动到这个文件中
qa-online/conf.py
import os
class Config(object):
"""项目的配置文件"""
# 数据库连接URI
SQLALCHEMY_DATABASE_URI = 'mysql://root:[email protected]/qa-online'
SQLALCHEMY_TRACK_MODIFICATIONS = True
同时我们需要将app.py中的代码进行,使用conf.py来进行数据库连接
qa-online/app.py
# 从配置文件中加载配置
app.config.from_object('conf.Config')
- ORM模型模块:model.py —这个我们之前已经划分好了
- 常量模块:在utils/constant.py
2. 试图文件中,实例化一个蓝图对象
qa-online中有两个模块的的蓝图,一个用户模块,一个是问题模块.每个模块的中蓝图都在一个单独的模块中,这里我们以accounts
中为例.
# 模块目录划分
├── templates
│ ├── accounts
│ │ ├── __init__.py
│ │ ├── templates
│ │ │ ├── login.html
│ │ │ ├── register.html
│ │ │ └── mine.html
│ │ └── view.py
view.py
from flask import Blueprint,render_template
accounts = Blueprint('accounts',__name__,
template_folder="templates",
static_folder="./assets")
@accounts.route('/mine')
def index():
""" 首页 """
return render_template('mine.html')
@accounts.route('/login')
def follow():
""" 关注 """
return render_template('login.html')
@accounts.route('/register')
def write():
""" 写文章,提问 """
return render_template('register.html')
3.注册蓝图
qa-online中有两个模块的的蓝图,一个用户模块,一个是问题模块.每个模块的中蓝图都在一个单独的模块中,使用是我们需要认证注册.
在app.py中进行注册蓝图
# 导入文件
from templates.accounts.views import accounts
# 注册蓝图
app.register_blueprint(accounts,url_prefix="/accounts")