I am working on a prototype to pull stocks ticks and dump them to a DB. I want to pass __tablename__ as a parameter to SQLAchemy so that stock ticks for a given stocks gets written down to its own table. (BTW, I am new to SQLAlchemy)
I referred this thread: Python Sqlalchemy - tablename as a variable
And came up with below code:
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() But it fails:
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 The error is quite obvious. But then I am unsure how to proceed with __tablename__ as a variable. Any pointers would be of great help.
Base.metadata.create_all(bind=engine)this line is creating the table. If I remove thecreate_modelsfunction and run the code by hardcoding__tablename__, the code works fine. It creates table on 1st run and on subsequent runs, it continues to inserts the records.class Stockout side of functioncreate_modelsclass Stockout side ofcreate_models, then how do I pass__tablename__as a variable.return Stockin your function and thenStock = create_models('ABCD')thentick = Stock('2019-02-12 09:15:00', '287')