forked from fastapi/sqlmodel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtutorial003.py
More file actions
43 lines (27 loc) · 1007 Bytes
/
tutorial003.py
File metadata and controls
43 lines (27 loc) · 1007 Bytes
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
43
from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def create_heroes(): # (1)
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson") # (2)
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)
with Session(engine) as session: # (3)
session.add(hero_1) # (4)
session.add(hero_2)
session.add(hero_3)
session.commit() # (5)
# (6)
def main(): # (7)
create_db_and_tables() # (8)
create_heroes() # (9)
if __name__ == "__main__": # (10)
main() # (11)