Skip to content

Commit 344c7a9

Browse files
committed
working api with async SQLAlchemy
Signed-off-by: Grant Ramsay <seapagan@gmail.com>
0 parents  commit 344c7a9

File tree

10 files changed

+2379
-0
lines changed

10 files changed

+2379
-0
lines changed

.gitignore

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
# File created using '.gitignore Generator' for Visual Studio Code: https://bit.ly/vscode-gig
2+
# Created by https://www.toptal.com/developers/gitignore/api/visualstudiocode,linux,python
3+
# Edit at https://www.toptal.com/developers/gitignore?templates=visualstudiocode,linux,python
4+
5+
### Linux ###
6+
*~
7+
8+
# temporary files which can be created if a process still has a handle open of a deleted file
9+
.fuse_hidden*
10+
11+
# KDE directory preferences
12+
.directory
13+
14+
# Linux trash folder which might appear on any partition or disk
15+
.Trash-*
16+
17+
# .nfs files are created when an open file is removed but is still being accessed
18+
.nfs*
19+
20+
### Python ###
21+
# Byte-compiled / optimized / DLL files
22+
__pycache__/
23+
*.py[cod]
24+
*$py.class
25+
26+
# C extensions
27+
*.so
28+
29+
# Distribution / packaging
30+
.Python
31+
build/
32+
develop-eggs/
33+
dist/
34+
downloads/
35+
eggs/
36+
.eggs/
37+
lib/
38+
lib64/
39+
parts/
40+
sdist/
41+
var/
42+
wheels/
43+
share/python-wheels/
44+
*.egg-info/
45+
.installed.cfg
46+
*.egg
47+
MANIFEST
48+
49+
# PyInstaller
50+
# Usually these files are written by a python script from a template
51+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
52+
*.manifest
53+
*.spec
54+
55+
# Installer logs
56+
pip-log.txt
57+
pip-delete-this-directory.txt
58+
59+
# Unit test / coverage reports
60+
htmlcov/
61+
.tox/
62+
.nox/
63+
.coverage
64+
.coverage.*
65+
.cache
66+
nosetests.xml
67+
coverage.xml
68+
*.cover
69+
*.py,cover
70+
.hypothesis/
71+
.pytest_cache/
72+
cover/
73+
74+
# Translations
75+
*.mo
76+
*.pot
77+
78+
# Django stuff:
79+
*.log
80+
local_settings.py
81+
db.sqlite3
82+
db.sqlite3-journal
83+
84+
# Flask stuff:
85+
instance/
86+
.webassets-cache
87+
88+
# Scrapy stuff:
89+
.scrapy
90+
91+
# Sphinx documentation
92+
docs/_build/
93+
94+
# PyBuilder
95+
.pybuilder/
96+
target/
97+
98+
# Jupyter Notebook
99+
.ipynb_checkpoints
100+
101+
# IPython
102+
profile_default/
103+
ipython_config.py
104+
105+
# pyenv
106+
# For a library or package, you might want to ignore these files since the code is
107+
# intended to run in multiple environments; otherwise, check them in:
108+
# .python-version
109+
110+
# pipenv
111+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
112+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
113+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
114+
# install all needed dependencies.
115+
#Pipfile.lock
116+
117+
# poetry
118+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
119+
# This is especially recommended for binary packages to ensure reproducibility, and is more
120+
# commonly ignored for libraries.
121+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
122+
#poetry.lock
123+
124+
# pdm
125+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
126+
#pdm.lock
127+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
128+
# in version control.
129+
# https://pdm.fming.dev/#use-with-ide
130+
.pdm.toml
131+
132+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
133+
__pypackages__/
134+
135+
# Celery stuff
136+
celerybeat-schedule
137+
celerybeat.pid
138+
139+
# SageMath parsed files
140+
*.sage.py
141+
142+
# Environments
143+
.env
144+
.venv
145+
env/
146+
venv/
147+
ENV/
148+
env.bak/
149+
venv.bak/
150+
151+
# Spyder project settings
152+
.spyderproject
153+
.spyproject
154+
155+
# Rope project settings
156+
.ropeproject
157+
158+
# mkdocs documentation
159+
/site
160+
161+
# mypy
162+
.mypy_cache/
163+
.dmypy.json
164+
dmypy.json
165+
166+
# Pyre type checker
167+
.pyre/
168+
169+
# pytype static type analyzer
170+
.pytype/
171+
172+
# Cython debug symbols
173+
cython_debug/
174+
175+
# PyCharm
176+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
177+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
178+
# and can be added to the global gitignore or merged into this file. For a more nuclear
179+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
180+
#.idea/
181+
182+
### VisualStudioCode ###
183+
.vscode/*
184+
!.vscode/settings.json
185+
!.vscode/tasks.json
186+
!.vscode/launch.json
187+
!.vscode/extensions.json
188+
!.vscode/*.code-snippets
189+
190+
# Local History for Visual Studio Code
191+
.history/
192+
193+
# Built Visual Studio Code Extensions
194+
*.vsix
195+
196+
### VisualStudioCode Patch ###
197+
# Ignore all local history of files
198+
.history
199+
.ionide
200+
201+
# Support for Project snippet scope
202+
.vscode/*.code-snippets
203+
204+
# Ignore code-workspaces
205+
*.code-workspace
206+
207+
# End of https://www.toptal.com/developers/gitignore/api/visualstudiocode,linux,python
208+
209+
# Custom rules (everything added below won't be overriden by 'Generate .gitignore File' if you use 'Update' option)

.vscode/launch.json

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
{
2+
// Use IntelliSense to learn about possible attributes.
3+
// Hover to view descriptions of existing attributes.
4+
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5+
"version": "0.2.0",
6+
"configurations": [
7+
{
8+
"name": "Python: Django",
9+
"type": "python",
10+
"request": "launch",
11+
"program": "${workspaceFolder}/manage.py",
12+
"args": ["runserver"],
13+
"django": true,
14+
"env": {
15+
"DEBUG": "1"
16+
}
17+
}
18+
]
19+
}

.vscode/settings.json

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
{
2+
"[python]": {
3+
"editor.codeActionsOnSave": {
4+
"source.organizeImports": true
5+
}
6+
},
7+
"autoDocstring.startOnNewLine": true,
8+
"beautify.language": {
9+
"html": ["htm", "html", "django-html"]
10+
},
11+
"editor.formatOnPaste": false,
12+
"emmet.includeLanguages": {
13+
"jinja-html": "html"
14+
},
15+
"emmet.triggerExpansionOnTab": true,
16+
"files.associations": {
17+
"**/*.html": "html",
18+
"**/requirements{/**,*}.{txt,in}": "pip-requirements",
19+
"**/templates/**/*": "django-txt",
20+
"**/templates/**/*.html": "jinja-html"
21+
},
22+
"files.eol": "\n",
23+
"files.exclude": {
24+
"**/__pycache__": true
25+
},
26+
"git.alwaysSignOff": true,
27+
"git.enableCommitSigning": true,
28+
"html.format.indentHandlebars": true,
29+
"html.format.templating": true,
30+
"python.analysis.extraPaths": [],
31+
"python.analysis.stubPath": "/home/seapagan/stubs",
32+
"python.analysis.typeCheckingMode": "basic",
33+
"python.formatting.blackArgs": ["--line-length=80"],
34+
"python.formatting.provider": "black",
35+
"python.languageServer": "Pylance",
36+
"python.linting.enabled": true,
37+
"python.linting.flake8Args": ["--max-line-length=80"],
38+
"python.linting.flake8Enabled": true,
39+
"python.linting.mypyEnabled": false,
40+
"python.linting.pydocstyleArgs": ["--convention=google"],
41+
"python.linting.pylintArgs": [],
42+
"python.linting.pylintEnabled": false,
43+
"python.linting.pylintUseMinimalCheckers": false,
44+
"python.pythonPath": "/home/seapagan/.pyenv/versions/calendar/bin/python",
45+
"python.sortImports.args": ["--profile", "black", "--src=${workspaceFolder}"],
46+
"python.testing.nosetestsEnabled": false,
47+
"python.testing.pytestArgs": ["tests"],
48+
"python.testing.pytestEnabled": true,
49+
"python.testing.unittestArgs": ["-v", "-s", "./tests", "-p", "*_test.py"],
50+
"python.testing.unittestEnabled": false,
51+
"testExplorer.addToEditorContextMenu": true
52+
}

LICENSE.txt

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) 2023 Grant Ramsay
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: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Simple example how to use FastAPI with Async SQLAlchemy 2.0
2+
3+
I've been using [FastAPI](https://fastapi.tiangolo.com/) and
4+
[SQLAlchemy](https://www.sqlalchemy.org/) combined with
5+
[encode/databases](https://www.encode.io/databases/) for a while now.
6+
7+
The `databases` package is a great wrapper around `SQLAlchemy` that allows you
8+
to use async/await with SQLAlchemy.
9+
10+
However, this does not seem be be actively maintained anymore. So I decided to
11+
give the new [Async
12+
SQLAlchemy](https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html) a try
13+
instead.
14+
15+
This repository contains a very simple example how to use FastAPI with Async
16+
SQLAlchemy 2.0.
17+
18+
## Installation
19+
20+
Clone the repository and install the dependencies. This project uses
21+
[Poetry](https://python-poetry.org/) for dependency management which shouyld be
22+
installed on your system.
23+
24+
```bash
25+
poetry install
26+
```
27+
28+
Then switch to the virtual environment:
29+
30+
```bash
31+
poetry shell
32+
```
33+
34+
## Usage
35+
36+
Run the server using `Uvicorn`:
37+
38+
```bash
39+
uvicorn main:app --reload
40+
```
41+
42+
Then open your browser at [http://localhost:8000](http://localhost:8000).
43+
44+
There is only one endpoint available: `/users`. It returns a list of all users
45+
for a `GET` request and creates a new user for a `POST` request.
46+
47+
## License
48+
49+
This project is licensed under the terms of the MIT license.
50+
51+
```pre
52+
MIT License
53+
54+
Copyright (c) 2023 Grant Ramsay
55+
56+
Permission is hereby granted, free of charge, to any person obtaining a copy
57+
of this software and associated documentation files (the "Software"), to deal
58+
in the Software without restriction, including without limitation the rights
59+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
60+
copies of the Software, and to permit persons to whom the Software is
61+
furnished to do so, subject to the following conditions:
62+
63+
The above copyright notice and this permission notice shall be included in all
64+
copies or substantial portions of the Software.
65+
66+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
67+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
68+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
69+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
70+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
71+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
72+
SOFTWARE.
73+
74+
```

db.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
2+
from sqlalchemy.orm import declarative_base, sessionmaker
3+
4+
DATABASE_URL = "postgresql+asyncpg://postgres:postgres@localhost/postgres"
5+
6+
engine = create_async_engine(DATABASE_URL, echo=False)
7+
Base = declarative_base()
8+
9+
10+
async_session = sessionmaker(
11+
engine, class_=AsyncSession, expire_on_commit=False # type: ignore
12+
)

0 commit comments

Comments
 (0)