创建表

概述

使用lessweb.plugin.database的create_all方法,可以根据DbModel的子类创建对应的数据库表。

限制

如果数据库表已经生成过,则操作会被忽略,也不能对表结构进行修改(ALTER)。

示例

gender.py

from enum import Enum
class Gender(Enum):
    MALE = 1
    FEMALE = 2

tables.py

from sqlalchemy import Column, Integer, Text, String, Enum
from lessweb.plugin.database import DbModel
from gender import Gender

class TblBook(DbModel):  # 表名默认为'TblBook'
    id = Column(Integer, primary_key=True)
    name = Column(Text)
    author = Column(String(64))

class TblUser(DbModel):
    __tablename__ = 'tbl_user'
    id = Column(Integer, primary_key=True)
    name = Column(String(64), comment='姓名')
    gender = Column(Enum(Gender))

init.py

from lessweb.plugin import database
from tables import TblBook, TblUser

dburi = 'mysql+mysqlconnector://root:pwd@localhost/proj'
database.init(dburi=dburi, echo=True, autoflush=True, autocommit=False)
database.create_all(TblBook, TblUser)
......