-
Notifications
You must be signed in to change notification settings - Fork 0
/
with_db.py
93 lines (69 loc) · 2.15 KB
/
with_db.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
from fastapi import FastAPI, HTTPException, Depends, status
from typing import Annotated
from sqlmodel import Field, Session, SQLModel, create_engine, select
app = FastAPI(
title="Location Finder API",
version="1.0.0",
servers=[
{
"url": "",
"description": "Development Server",
}
],
)
class Location(SQLModel, table=True):
name: str = Field(index=True, primary_key=True)
location: str
database_url = "paste your database url here"
engine = create_engine(database_url)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
@app.on_event("startup")
def on_startup():
create_db_and_tables()
@app.get("/persons/")
def read_all_persons():
"""
Retrieves all persons from the database.
Returns:
list: A list of Location objects representing the persons.
"""
with Session(engine) as session:
loc_data = session.exec(select(Location)).all()
return loc_data
@app.post("/person/")
def create_person(person_data: Location):
"""
Creates a new person record in the database.
Args:
person_data (Location): name and location of person.
Returns:
Location: The created person record that is name and location of person.
"""
with Session(engine) as session:
session.add(person_data)
session.commit()
session.refresh(person_data)
return person_data
# dependency injection function
def get_location_or_404(name: str) -> Location:
with Session(engine) as session:
loc_data = session.exec(select(Location).where(Location.name == name)).first()
if not loc_data:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"No location found for {name}",
)
return loc_data
@app.get("/location/{name}")
def get_person_location(
name: str, location: Annotated[Location, Depends(get_location_or_404)]
):
"""
Retrieve the location of a person by their name.
Args:
name (str): The name of the person.
Returns:
Location: The location of the person.
"""
return location