generated from pamelafox/sqlalchemy-sqlite-playground
-
Notifications
You must be signed in to change notification settings - Fork 25
/
main_sqlalchemy.py
42 lines (32 loc) · 1.12 KB
/
main_sqlalchemy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import os
from dotenv import load_dotenv
from sqlalchemy import String, create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
# Define the models
class Base(DeclarativeBase):
pass
class Restaurant(Base):
__tablename__ = "restaurants"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String)
address: Mapped[str] = mapped_column(String, nullable=True)
# Connect to the database
load_dotenv(".env", override=True)
DBUSER = os.environ["DBUSER"]
DBPASS = os.environ["DBPASS"]
DBHOST = os.environ["DBHOST"]
DBNAME = os.environ["DBNAME"]
DATABASE_URI = f"postgresql://{DBUSER}:{DBPASS}@{DBHOST}/{DBNAME}"
if DBHOST != "localhost":
DATABASE_URI += "?sslmode=require"
engine = create_engine(DATABASE_URI, echo=True)
# Create tables in database
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
# Insert data and issue queries
with Session(engine) as session:
for i in range(10):
session.add(Restaurant(name=f"Cheese Shop #{i}"))
session.commit()
query = select(Restaurant)
results = session.execute(query)