The version I tried.
In [1]: import sqlalchemy
In [2]: sqlalchemy.__version__
Out[2]: '1.0.5'
If you pass Metadata or engine to sqlalchemy.Table ()
, you can get the Table
object that can be passed to session as it is.
Make a dict of {<table name>: sqlalchemy.Table}
and place it in a wide area of the module.
dbs.py
# -*- coding: utf-8 -*-
import sqlalchemy
import sqlalchemy.ext.declarative
Base = sqlalchemy.ext.declarative.declarative_base()
url = 'mysql://[email protected]/employees?charset=utf8'
engine = sqlalchemy.create_engine(url, echo=False)
tables = { name: sqlalchemy.Table(name, Base.metadata, autoload=True, autoload_with=engine)
for name in engine.table_names()
}
globals().update(tables)
Session = sqlalchemy.orm.sessionmaker(bind=engine)
session = Session()
ʻEmployees` Get all records from the table. (MySQL sample)
select.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import dbs
for x in dbs.session.query(dbs.employees):
print x
TODO: You might want to export it in the form of a static class.
You can dynamically lick the table and spit it out like this.
Such a shape
class Student(Base):
__tablename__ = 'students'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
name = sqlalchemy.Column(sqlalchemy.String(255))
kana = sqlalchemy.Column(sqlalchemy.String(255))
def __repr__(self):
return '<name=%s, kana=%s>' % (self.name, self.kana)
Recommended Posts