python - SQLAlchemy:__tablename__ 作为变量

标签 python sqlalchemy

我正在开发一个原型(prototype)来提取股票价格并将它们转储到数据库中。我想将 __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__ 作为变量。任何指针都会有很大帮助。

最佳答案

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有关范围的更多详细信息。

关于python - SQLAlchemy:__tablename__ 作为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54646044/

相关文章:

python - 如何有可能在 Flask Python 中用 2 个表调用 db.session.query 中的列名?

python - SQLAlchemy 查询与多列元组上的比较

python - 我的 SQLAlchemy MySQL 连接总是以休眠结束,这很奇怪吗?

python - 如何在 Elastic Beanstalk 上启动时运行一次 python 脚本

java - 从 Python 程序中使用 -Xms 和 -Xmx 参数执行 jar 文件

mysql - Django 连接池和时间字段

python - 带有参数的 SQLAlchemy NOT IN 子句

python - 计算和存储每日、每周、每月和每年的平均数据

python - 从 python 中导入的脚本中退出

python - 将 Python Flask 应用程序拆分为多个文件