时间:2021-07-01 10:21:17 帮助过:21人阅读
#!/usr/bin/env python # -*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Index from sqlalchemy.orm import sessionmaker,relationship from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/ttt",max_overflow=5) #连接数据库 Base = declarative_base() #创建单表: class Users(Base): #类必须要继承Base __tablename__ = ‘users‘ #表名 id = Column(Integer,primary_key=True) #创建列 name = Column(String(32)) extra = Column(String(16)) __table_args__ = ( UniqueConstraint(‘id‘,‘name‘,name=‘centos‘), #联合索引 Index(‘ix_id_name‘,‘name‘,‘extra‘), ) #一对多 class Favor(Base): __tablename__ = ‘favor‘ nid = Column(Integer,primary_key=True) caption = Column(String(50),default=‘red‘,unique=True) class Person(Base): __tablename__ = ‘person‘ nid = Column(Integer,primary_key=True) name = Column(String(32),index=True,nullable=True) favor_id = Column(Integer,ForeignKey("favor.nid")) #根上一个favor的nid做外键 #多对多 class ServerToGroup(Base): __tablename__ = ‘servertogroup‘ id = Column(Integer,primary_key=True,autoincrement=True) hostname = Column(String(64),unique=True,nullable=False) class Group(Base): __tablename__ = ‘group‘ id = Column(Integer,primary_key=True) name = Column(String(64),unique=True,nullable=False) class Server(Base): __tablename__ = ‘server‘ id = Column(Integer,primary_key=True,autoincrement=True) hostname = Column(String(64),unique=True,nullable=False) port = Column(Integer,default=22) # def init_db(): # Base.metadata.create_all(engine) # init_db() #创建 def drop_db(): Base.metadata.drop_all(engine) drop_db() #删除
day13 SQLAlchemy
标签:make env 多对多 配置文件 rem create str extra title