Jun-01-2023, 02:57 PM
(This post was last modified: Jun-02-2023, 01:14 PM by Calab.
Edit Reason: Fix commit()
)
I'm trying to understand how to use SQLAlchemy. I've written a piece of code that should simply add one record to an existing database. When I run the code I don't get an error, but nothing writes to the database. I'm obviously doing something wrong, but I can't spot it.
I'm using Python 3.7.11. SQLAlchemy is 2.0.12.
I'm using Python 3.7.11. SQLAlchemy is 2.0.12.
#!/cmts/fastapi/sv/venv/bin/python3
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from sqlalchemy import Column, Integer, String, Date
# Location of the test catalog database
SQLALCHEMY_DATABASE_URL = "sqlite:///./test_catalog.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
Base = declarative_base()
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
class Test(Base):
__tablename__ = "catalog"
id = Column(String, primary_key=True) # Identifying ID for this test
parent_id = Column(String) # ID of test that this was generated from, if not a parent test
request_id = Column(String) # UUID ID used to group multiple tests that are submitted at the same time
test_type = Column(String) # Type of test: Online, Impaired, Network, etc...
target = Column(String) # Target for this test
user = Column(String) # Username of who initiated the test
submitted = Column(Date) # When was this test submitted
started = Column(Date) # When was this test started
ended = Column(Date) # When was this test completed
progress = Column(Integer, default=0) # Progress indicator for this test, from 0 to 100
state = Column(String, default="New") # State of the test: New, Running, Done, Error
result = Column(String) # JSON results of the test. Compressed?
def get_db():
try:
db: Session = SessionLocal()
return db
except Exception as e:
print(e)
# finally:
# db.close()
Base.metadata.create_all(bind=engine)
db = get_db()
test_model = Test()
test_model.id = "1234567890"
test_model.parent_id = None
test_model.request_id = "0987654321"
test_model.target = "target"
test_model.user = "user"
test_model.test_type = "test"
test_model.submitted = datetime.now()
test_model.started = None
test_model.ended = None
test_model.progress = 0
test_model.state = "New"
test_model.result = None
db.add(test_model)
db.commit()
print("Added")
print(db.query(Test).all())
db.close()I check my database, and there are no rows:$ sqlite3 test_catalog.db SQLite version 3.7.17 2013-05-20 00:56:22 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> select * from catalog; sqlite>
