FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
sqlmodel/docs_src/tutorial/fastapi/read_one/tutorial001.py at docs · PookieBuns/sqlmodel · GitHub
PookieBuns
sqlmodel
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
sqlmodel
/
docs_src
/
tutorial
/
fastapi
/
read_one
/
tutorial001.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
67 lines (43 loc) · 1.52 KB
Breadcrumbs
sqlmodel
/
docs_src
/
tutorial
/
fastapi
/
read_one
/
tutorial001.py
Copy path
File metadata and controls
67 lines (43 loc) · 1.52 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
from
typing
import
List
,
Optional
from
fastapi
import
FastAPI
,
HTTPException
from
sqlmodel
import
Field
,
Session
,
SQLModel
,
create_engine
,
select
class
HeroBase
(
SQLModel
):
name
:
str
=
Field
(
index
=
True
)
secret_name
:
str
age
:
Optional
[
int
]
=
Field
(
default
=
None
,
index
=
True
)
class
Hero
(
HeroBase
,
table
=
True
):
id
:
Optional
[
int
]
=
Field
(
default
=
None
,
primary_key
=
True
)
class
HeroCreate
(
HeroBase
):
pass
class
HeroRead
(
HeroBase
):
id
:
int
sqlite_file_name
=
"database.db"
sqlite_url
=
f"sqlite:///
{
sqlite_file_name
}
"
connect_args
=
{
"check_same_thread"
:
False
}
engine
=
create_engine
(
sqlite_url
,
echo
=
True
,
connect_args
=
connect_args
)
def
create_db_and_tables
():
SQLModel
.
metadata
.
create_all
(
engine
)
app
=
FastAPI
()
@
app
.
on_event
(
"startup"
)
def
on_startup
():
create_db_and_tables
()
@
app
.
post
(
"/heroes/"
,
response_model
=
HeroRead
)
def
create_hero
(
hero
:
HeroCreate
):
with
Session
(
engine
)
as
session
:
db_hero
=
Hero
.
from_orm
(
hero
)
session
.
add
(
db_hero
)
session
.
commit
()
session
.
refresh
(
db_hero
)
return
db_hero
@
app
.
get
(
"/heroes/"
,
response_model
=
List
[
HeroRead
])
def
read_heroes
():
with
Session
(
engine
)
as
session
:
heroes
=
session
.
exec
(
select
(
Hero
)).
all
()
return
heroes
@
app
.
get
(
"/heroes/{hero_id}"
,
response_model
=
HeroRead
)
def
read_hero
(
hero_id
:
int
):
with
Session
(
engine
)
as
session
:
hero
=
session
.
get
(
Hero
,
hero_id
)
if
not
hero
:
raise
HTTPException
(
status_code
=
404
,
detail
=
"Hero not found"
)
return
hero
Back
|
FazBrowse Home
|
New Git URL