数据模型

该项目是一个 TODO 应用,可以对任务清单进行增加、修改、删除等,相应地,我们需要设计一个数据模型来存储相应的数据和状态。不难想到,表的字段主要有以下几个:

  • id: 标识每条记录的字段,是表的主键,Integer 类型;
  • title: 即任务清单的标题,String 类型;
  • posted_on: 任务创建时间,DATE 类型;
  • status: 任务的状态,Boolean 类型;

因此,我们的数据模型定义如下 (完整代码参考这里):

  1. # -*- coding: utf-8 -*-
  2. from application.extensions import db
  3. from datetime import datetime
  4. __all__ = ['Todo']
  5. class Todo(db.Model):
  6. """数据模型"""
  7. __tablename__ = 'todo'
  8. id = db.Column(db.Integer, primary_key=True)
  9. title = db.Column(db.String(255), nullable=False)
  10. posted_on = db.Column(db.Date, default=datetime.utcnow)
  11. status = db.Column(db.Boolean(), default=False)
  12. def __init__(self, *args, **kwargs):
  13. super(Todo, self).__init__(*args, **kwargs)
  14. def __repr__(self):
  15. return "<Todo '%s'>" % self.title

创建数据库

这里,我们使用 Flask-Migrate 插件管理数据库的迁移和升级,详细用法可以查看 Flask-Migrate

在项目的根目录下按顺序执行如下命令,生成 migratios 文件夹、数据迁移脚本和更新数据库。

  1. $ python manage.py db init # 初始化,生成 migratios 文件夹
  2. Creating directory /Users/admin/flask-todo/migrations ... done
  3. Creating directory /Users/admin/flask-todo/migrations/versions ... done
  4. Generating /Users/admin/flask-todo/migrations/alembic.ini ... done
  5. Generating /Users/admin/flask-todo/migrations/env.py ... done
  6. Generating /Users/admin/flask-todo/migrations/env.pyc ... done
  7. Generating /Users/admin/flask-todo/migrations/README ... done
  8. Generating /Users/admin/flask-todo/migrations/script.py.mako ... done
  9. Please edit configuration/connection/logging settings in '/Users/admin/flask-
  10. todo/migrations/alembic.ini' before proceeding.
  11. $ python manage.py db migrate # 自动创建迁移脚本
  12. INFO [alembic.runtime.migration] Context impl SQLiteImpl.
  13. INFO [alembic.runtime.migration] Will assume non-transactional DDL.
  14. INFO [alembic.autogenerate.compare] Detected added table 'todo'
  15. Generating /Users/admin/flask-todo/migrations/versions/70215a3905e0_.py ... done
  16. $ python manage.py db upgrade # 更新数据库
  17. INFO [alembic.runtime.migration] Context impl SQLiteImpl.
  18. INFO [alembic.runtime.migration] Will assume non-transactional DDL.
  19. INFO [alembic.runtime.migration] Running upgrade -> 70215a3905e0, empty message