Python——Flask框架——程序的结构
一、项目结构
|-flasky |-app Flask程序一般都保存在这里 |-templates/ |-static/ |main/ |-__init__.py |-errors.py |-forms.py |-views.py |-__init__.py |-email.py 电子邮件函数 |-models.py 数据库模型 |-migrations/ 包含数据库迁移的脚本 |-tests/ 单元测试 |-__init__.py |test*.py |-venv/ 包含Python虚拟环境 |requirements.txt 列出所有依赖包 |config.py 存储配置 |manage.py 用于启动程序
二、config.py程序配置(实例)
基类中包含通用配置,子类分别定义了专用配置
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config : SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string' SQLALCHEMY_COMMIT_ON_TEARDOWN = True FLASKY_MAIL_SUBJECT_PREFIX = '[Flasky]' FLASKY_MAIL_SENDER = 'Flasky Admin <flasky@example.com>' FLASKY_ADMIN = os.environ.get('FLASKY_ADMIN') @staticmethod def init_app(app): pass class DevelopmentConfig(Config): DEBUG = True MAIL_SERVER = 'smtp.cooglemail.com' MAIL_PORT = 587 MAIL_USE_TLS = True MAIL_USERNAME = os.environ.get('MAIL_ISERNAME') MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD') SQLALCHEMYU_DATABASE_URL = os.environ.get('SQLALCHEMYU_DATABASE_URL') or 'sqlite:///' + os.path.join(basedir,'data.sqlite') class TestingConfig(Config): TESTING = True SQLALCHEMYU_DATABASE_URL = os.environ.get('TEST_DATABASE_URL') or 'sqlite:///' + os.path.join(basedir,'data-test.sqlite') class ProductionConfig(Config): SQLALCHEMYU_DATABASE_URL = os.environ.get('DATABASE_URL') or 'sqlite:///' + os.path.join(basedir,'data.sqlite') config = { 'development' : DevelopmentConfig, 'testing' : TestingConfig, 'production' : ProductionConfig, 'default' : DevelopmentConfig }
三、程序工厂函数
四、蓝本实现程序功能
**在蓝本中编写错误处理程序稍有不同,如果使用errorhandler修饰器,那么只有蓝本中的错误才能出发处理程序,要想注册程序全局的错误处理程序,必须使用app_eerrorhandler
(1)app/main/views.py蓝本定义的程序路由
from datetime import datetime from flask import render_template,session,redirect,url_for #下面引用的函数是错误的,可能是未在Flask框架下 from . import main from .forms import NameForm from .. import db from ..models import User @main.route('/',menthods=['GET','POST']) def index(): form = NameForm() if form.validate_on_sumbit(): #... return redirect(url_for('.index')) return render_template('index.html',form=form,name=session.get('name'),known=session.get('known',False),current_time=datetime.utcnoww())
五、启动脚本(manage.py)
import os from app import create_app,db from app.models import User,Role from flask.ext.script import Manager,Shell from flask.ext.migrate import Migrate,MigrateCommand app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app) def make_shell_context(): return dict(app=app,db=db,User=User,Role=Role) manager.add.command('shell',Shell(make_context=make_shell_context)) manager.add.command('db',MigrateCommand) if __name__ == '__main__': manager.run()
**这个脚本先创建程序,如果定义了环境变量FLASK_CONFIG,则从中读取配置名;否则使用默认配置,然后初始化Flask-Script,Flask-Migrate和位Python shell定义的上下文。
六、需求文件(requirements.txt)
requirements.txt文件,用户记录所有依赖包机器精准的版本号
安装对应依赖包的版本号: pip install -r requirements.txt
七、单元测试(test.py)