Skip to content

Commit c315966

Browse files
committed
init
0 parents  commit c315966

17 files changed

+455
-0
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
__pycache__
2+
env
3+
htmlcov
4+
.coverage

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2021 Michael Herman
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# FastAPI + SQLModel + Alembic
2+
3+
Sample FastAPI project that uses async SQLAlchemy, SQLModel, Postgres, Alembic, and Docker.
4+
5+
## Getting Started
6+
7+
```sh
8+
$ docker-compose up -d --build
9+
$ docker-compose exec web alembic upgrade head
10+
```
11+
12+
Sanity check: [http://localhost:8004/ping](http://localhost:8004/ping)
13+
14+
Add a song:
15+
16+
```sh
17+
$ curl -d '{"name":"Midnight Fit", "artist":"Mogwai", "year":"2021"}' -H "Content-Type: application/json" -X POST http://localhost:8004/songs
18+
```
19+
20+
Get all songs: [http://localhost:8004/songs](http://localhost:8004/songs)

docker-compose.yml

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
version: '3.8'
2+
3+
services:
4+
5+
web:
6+
build: ./project
7+
command: uvicorn app.main:app --reload --workers 1 --host 0.0.0.0 --port 8000
8+
volumes:
9+
- ./project:/usr/src/app
10+
ports:
11+
- 8004:8000
12+
environment:
13+
- DATABASE_URL=postgresql+asyncpg://postgres:postgres@db:5432/foo
14+
depends_on:
15+
- db
16+
17+
db:
18+
image: postgres:13.4
19+
expose:
20+
- 5432
21+
environment:
22+
- POSTGRES_USER=postgres
23+
- POSTGRES_PASSWORD=postgres
24+
- POSTGRES_DB=foo

project/.dockerignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.dockerignore
2+
Dockerfile

project/Dockerfile

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# pull official base image
2+
FROM python:3.9-slim-buster
3+
4+
# set working directory
5+
WORKDIR /usr/src/app
6+
7+
# set environment variables
8+
ENV PYTHONDONTWRITEBYTECODE 1
9+
ENV PYTHONUNBUFFERED 1
10+
11+
# install system dependencies
12+
RUN apt-get update \
13+
&& apt-get -y install netcat gcc postgresql \
14+
&& apt-get clean
15+
16+
# install python dependencies
17+
RUN pip install --upgrade pip
18+
COPY ./requirements.txt .
19+
RUN pip install -r requirements.txt
20+
21+
# add app
22+
COPY . .

project/alembic.ini

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
# A generic, single database configuration.
2+
3+
[alembic]
4+
# path to migration scripts
5+
script_location = migrations
6+
7+
# template used to generate migration files
8+
# file_template = %%(rev)s_%%(slug)s
9+
10+
# sys.path path, will be prepended to sys.path if present.
11+
# defaults to the current working directory.
12+
prepend_sys_path = .
13+
14+
# timezone to use when rendering the date within the migration file
15+
# as well as the filename.
16+
# If specified, requires the python-dateutil library that can be
17+
# installed by adding `alembic[tz]` to the pip requirements
18+
# string value is passed to dateutil.tz.gettz()
19+
# leave blank for localtime
20+
# timezone =
21+
22+
# max length of characters to apply to the
23+
# "slug" field
24+
# truncate_slug_length = 40
25+
26+
# set to 'true' to run the environment during
27+
# the 'revision' command, regardless of autogenerate
28+
# revision_environment = false
29+
30+
# set to 'true' to allow .pyc and .pyo files without
31+
# a source .py file to be detected as revisions in the
32+
# versions/ directory
33+
# sourceless = false
34+
35+
# version location specification; This defaults
36+
# to migrations/versions. When using multiple version
37+
# directories, initial revisions must be specified with --version-path.
38+
# The path separator used here should be the separator specified by "version_path_separator"
39+
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
40+
41+
# version path separator; As mentioned above, this is the character used to split
42+
# version_locations. Valid values are:
43+
#
44+
# version_path_separator = :
45+
# version_path_separator = ;
46+
# version_path_separator = space
47+
version_path_separator = os # default: use os.pathsep
48+
49+
# the output encoding used when revision files
50+
# are written from script.py.mako
51+
# output_encoding = utf-8
52+
53+
sqlalchemy.url = postgresql+asyncpg://postgres:postgres@db:5432/foo
54+
55+
56+
[post_write_hooks]
57+
# post_write_hooks defines scripts or Python functions that are run
58+
# on newly generated revision scripts. See the documentation for further
59+
# detail and examples
60+
61+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
62+
# hooks = black
63+
# black.type = console_scripts
64+
# black.entrypoint = black
65+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
66+
67+
# Logging configuration
68+
[loggers]
69+
keys = root,sqlalchemy,alembic
70+
71+
[handlers]
72+
keys = console
73+
74+
[formatters]
75+
keys = generic
76+
77+
[logger_root]
78+
level = WARN
79+
handlers = console
80+
qualname =
81+
82+
[logger_sqlalchemy]
83+
level = WARN
84+
handlers =
85+
qualname = sqlalchemy.engine
86+
87+
[logger_alembic]
88+
level = INFO
89+
handlers =
90+
qualname = alembic
91+
92+
[handler_console]
93+
class = StreamHandler
94+
args = (sys.stderr,)
95+
level = NOTSET
96+
formatter = generic
97+
98+
[formatter_generic]
99+
format = %(levelname)-5.5s [%(name)s] %(message)s
100+
datefmt = %H:%M:%S

project/app/__init__.py

Whitespace-only changes.

project/app/db.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import os
2+
3+
from sqlmodel import SQLModel
4+
5+
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
6+
from sqlalchemy.orm import sessionmaker
7+
8+
9+
DATABASE_URL = os.environ.get("DATABASE_URL")
10+
11+
engine = create_async_engine(DATABASE_URL, echo=True)
12+
13+
14+
async def create_db_and_tables():
15+
async with engine.begin() as conn:
16+
# await conn.run_sync(SQLModel.metadata.drop_all)
17+
await conn.run_sync(SQLModel.metadata.create_all)
18+
19+
20+
async def get_session() -> AsyncSession:
21+
async_session = sessionmaker(
22+
engine, class_=AsyncSession, expire_on_commit=False
23+
)
24+
async with async_session() as session:
25+
yield session

project/app/main.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from fastapi import Depends, FastAPI
2+
from sqlalchemy.ext.asyncio import AsyncSession
3+
from sqlalchemy import select
4+
5+
from app.db import get_session, create_db_and_tables
6+
from app.models import Song, SongCreate
7+
8+
app = FastAPI()
9+
10+
11+
@app.get("/ping")
12+
async def pong():
13+
return {"ping": "pong!"}
14+
15+
16+
@app.get("/songs", response_model=list[Song])
17+
async def get_songs(session: AsyncSession = Depends(get_session)):
18+
result = await session.execute(select(Song))
19+
songs = result.scalars().all()
20+
return [Song(name=song.name, artist=song.artist, year=song.year, id=song.id) for song in songs]
21+
22+
23+
@app.post("/songs")
24+
async def add_song(song: SongCreate, session: AsyncSession = Depends(get_session)):
25+
song = Song(name=song.name, artist=song.artist, year=song.year)
26+
session.add(song)
27+
await session.commit()
28+
return song

0 commit comments

Comments
 (0)