SQLAlchemy:__tablename__作为变量

时间:2019-02-12 08:49:51

标签: python sqlalchemy

我正在研究一个原型,以提取股票价格变动并将其转储到数据库中。我想将__tablename__作为参数传递给SQLAchemy,以便将给定股票的股票报价记录到其自己的表中。 (顺便说一句,我是SQLAlchemy的新手)

我提到了这个主题:Python Sqlalchemy - tablename as a variable

并提出了以下代码:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy import Column, String, Integer, Date


Base = declarative_base()


def create_models(tablename):

    class Stock(Base):

        __tablename__ = tablename

        timestamp = Column(String, primary_key=True)
        ltp = Column(String)

        def __init__(self, timestamp, ltp):
            self.timestamp = timestamp
            self.ltp = ltp

create_models('ABCD')

engine = create_engine('sqlite:////ticks.db')
Base.metadata.create_all(bind=engine)

session_factory = sessionmaker(bind=engine)
Session = scoped_session(session_factory)()

tick = Stock('2019-02-12 09:15:00', '287')
Session.merge(tick)
Session.commit()

但是失败了:

Traceback (most recent call last):
  File "quickies.py", line 32, in <module>
    tick = Stock('2019-02-12 09:15:00', '287')
NameError: name 'Stock' is not defined

错误非常明显。但是然后我不确定如何将__tablename__用作变量。任何指针都会有很大帮助。

1 个答案:

答案 0 :(得分:1)

您的Stock类的范围仅限于create_models函数。要在函数外部创建此类的对象,您可以从函数中返回该类,然后使用它。

看看下面的解决方案:

def create_models(tablename):

    class Stock(Base):

        __tablename__ = tablename

        timestamp = Column(String, primary_key=True)
        ltp = Column(String)

        def __init__(self, timestamp, ltp):
            self.timestamp = timestamp
            self.ltp = ltp
    return Stock #return the class 

Stock = create_models('ABCD')
tick = Stock('2019-02-12 09:15:00', '287')

请查看Python scope tutorial,以获取与范围有关的更多详细信息。