基于SQLAlchemy类自动生成数据库表

2024-09-29 00:23:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我对SQLAlchemy很陌生,我喜欢它。现在我正在做很多手工的事情,我想做的事情更'Python'和动态。

因此作为一个例子,我有一个简短的脚本,它手动创建/定义一个表,然后是一个函数,将数据插入到该表中。

数据库连接

import os
from sqlalchemy import *
from sqlalchemy import schema, types
from sqlalchemy.ext.declarative import declarative_base  

db_url = os.environ.get('DATABASE_URL')
engine = create_engine(db_url)
Base = declarative_base(engine)
meta = Base.metadata

表格定义

file_paths = Table('file_paths', meta,
    Column('table_id', Integer, primary_key = True),
    Column('fullpath', String(255)),
    Column('filename', String(255)),
    Column('extension', String(255)),
    Column('created', String(255)),
    Column('modified', String(255)),
    Column('size', Integer),
    Column('owner', String(255)),
    Column('permissions', Integer),
    mysql_engine='InnoDB',
)
file_paths.drop(engine, checkfirst = False)
file_paths.create(engine, checkfirst = True)

插入函数将字符串和列表作为参数

def push_to_db(fullpath, fileInfo):
    i = file_paths.insert()
    i.execute(  fullpath    = str(fullpath), 
            filename    = str(fileInfo[0]),
            extension   = str(fileInfo[1]),
            created     = str(fileInfo[2]),
            modified    = str(fileInfo[3]),
            size        = str(fileInfo[4]),
            owner       = str(fileInfo[5]),
            permissions = str(fileInfo[6]),
         )

这是可行的,但它是丑陋的,并采取了一个教程,我发现在网上某处。我的目标是使这些行动充满活力。

示例类

class FileMeta(object):
    def __init__(self, fullPathFileName, filename):
        self.fullPathFileName = fullPathFileName
        self.filename = filename
        self.extension = os.path.splitext(self.filename)[1].lower()
        ...

    def fileMetaList(self):
        return [self.filename, self.extension, self.created, self.modified,\
                self.size, self.owner, self.permissions]

下面是一个场景:给定一个类对象

  1. 根据类成员变量动态定义表
    • 列号和列名应与变量名相对应
    • 或对应于类变量列表中该变量的索引
  2. 编写一个函数,可以将类中的数据插入到相应的动态创建的表中

我的直觉告诉我,这就是SQLAlchemy的好处所在。有人能告诉我一个好的教程或参考资料,可以概述这个过程吗?


Tags: 函数importselfstring定义osextensioncolumn
1条回答
网友
1楼 · 发布于 2024-09-29 00:23:20

您要改用declarative extension

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class FilePaths(Base):
    __tablename__ = 'file_paths'
    __table_args__ = {'mysql_engine':'InnoDB'}

    table_id = Column(Integer, primary_key=True)
    fullpath = Column(String(255))
    filename = Column(String(255))
    extension = Column(String(255))
    created = Column(String(255))
    modified = Column(String(255))
    size = Column(Integer)
    owner = Column(String(255))
    permissions = Column(Integer)

Base.metadata.create_all(engine)

您可以根据需要定义自己的__init__()以及其他方法,然后创建这些方法的实例以插入新行。

请参阅SQLAlchemy's own ORM tutorial

相关问题 更多 >