创建一个虚拟环境bbs,并安装flask框架
#cmd进入DOS窗口 mkvirtualenv bbs pip install flask
在本地磁盘D新建项目目录:bbs
打开pycharm,创建flask项目
新建两个文件,config.py( 配置文件)、exts.py(用于第三方库)
项目分为前台(front)、后台(cms)、公共(common)
因此这里配置上面3个蓝图
新建一个python package命名为apps,在apps下新建三个python package分别命名为:cms、common、front
这3个蓝图都会有自己的数据模型和视图,则在它们各自下新建文件models.py、views.py,前台和后台肯定会有表单验证,因此也新建forms.py
cms.view.py
from flask import Blueprint bp = Blueprint('cms', __name__, url_prefix='/cms') @bp.route('/') def index(): return 'cms index'
common.py
from flask import Blueprint bp = Blueprint('common', __name__, url_prefix='/common') @bp.route('/') def index(): return 'common index'
front.py
from flask import Blueprint bp = Blueprint('front', __name__) #因为前台是直接访问就不用加url_prefix @bp.route('/') def index(): return 'front index'
编辑cms.__init__.py、common.__init__.py、front.__init__.py,这样做的好处就是可以这样导入蓝图:from apps.cms import bp
from .views import bp
编辑bbs.py注册蓝图,该文件不编辑任何视图及url
from flask import Flask import config from apps.cms import bp as cms_bp from apps.common import bp as common_bp from apps.front import bp as front_bp app = Flask(__name__) app.config.from_object(config) #引入配置文件 app.register_blueprint(cms_bp) app.register_blueprint(common_bp) app.register_blueprint(front_bp) if __name__ == '__main__': app.run()
编辑config.py开启DEBUG模式
DEBUG = True
最后启动项目
配置数据库信息创建数据库
MySQL创建数据库bbs
address: 127.0.0.1:3306
database: bbs
username: root
password: 123456
安装相关的库
workon bbs #进入虚拟环境 pip install pymysql pip install flask-sqlalchemy pip install flask-script pip install flask-migrate
编辑配置文件config.py配置数据库连接信息
DEBUG = True #MySQL Database HOST = '127.0.0.1' PORT = '3306' USERNAME = 'root' PASSWORD = '123456' DATABASE = 'bbs' DB_URI = 'mysql+pymysql://{username}:{password}@{host}:{port}/{db}?charset-utf8'.format(username=USERNAME, password=PASSWORD, host=HOST, port=PORT, db=DATABASE) SQLALCHEMY_DATABASE_URI = DB_URI SQLALCHEMY_TRACK_MODIFICATIONS = False
编辑exts.py初始化SQLAlchemy
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
创建一个manage.py用来写迁移脚本
from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from bbs import app from exts import db manager = Manager(app) Migrate(app, db) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()
在主程序bbs.py给db传入app
from exts import db ... db.init_app(app)
初始化迁移脚本
D:bs>workon flask-env
(flask-env) D:bs>python manage.py db init