我对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]
下面是一个场景:给定一个类对象
我的直觉告诉我,这就是SQLAlchemy的好处所在。有人能告诉我一个好的教程或参考资料,可以概述这个过程吗?
您要改用declarative extension:
您可以根据需要定义自己的
__init__()
以及其他方法,然后创建这些方法的实例以插入新行。请参阅SQLAlchemy's own ORM tutorial。
相关问题 更多 >
编程相关推荐