-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
10 changed files
with
2,031 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
[flake8] | ||
max_line_length = 100 | ||
per-file-ignores = | ||
**/__init__.py:F401 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,159 @@ | ||
# Created by https://www.toptal.com/developers/gitignore/api/python | ||
# Edit at https://www.toptal.com/developers/gitignore?templates=python | ||
|
||
### Python ### | ||
# Byte-compiled / optimized / DLL files | ||
__pycache__/ | ||
*.py[cod] | ||
*$py.class | ||
|
||
# C extensions | ||
*.so | ||
|
||
# Distribution / packaging | ||
.Python | ||
build/ | ||
develop-eggs/ | ||
dist/ | ||
downloads/ | ||
eggs/ | ||
.eggs/ | ||
lib/ | ||
lib64/ | ||
parts/ | ||
sdist/ | ||
var/ | ||
wheels/ | ||
share/python-wheels/ | ||
*.egg-info/ | ||
.installed.cfg | ||
*.egg | ||
MANIFEST | ||
|
||
# PyInstaller | ||
# Usually these files are written by a python script from a template | ||
# before PyInstaller builds the exe, so as to inject date/other infos into it. | ||
*.manifest | ||
*.spec | ||
|
||
# Installer logs | ||
pip-log.txt | ||
pip-delete-this-directory.txt | ||
|
||
# Unit test / coverage reports | ||
htmlcov/ | ||
.tox/ | ||
.nox/ | ||
.coverage | ||
.coverage.* | ||
.cache | ||
nosetests.xml | ||
coverage.xml | ||
*.cover | ||
*.py,cover | ||
.hypothesis/ | ||
.pytest_cache/ | ||
cover/ | ||
|
||
# Translations | ||
*.mo | ||
*.pot | ||
|
||
# Django stuff: | ||
*.log | ||
local_settings.py | ||
db.sqlite3 | ||
db.sqlite3-journal | ||
|
||
# Flask stuff: | ||
instance/ | ||
.webassets-cache | ||
|
||
# Scrapy stuff: | ||
.scrapy | ||
|
||
# Sphinx documentation | ||
docs/_build/ | ||
|
||
# PyBuilder | ||
.pybuilder/ | ||
target/ | ||
|
||
# Jupyter Notebook | ||
.ipynb_checkpoints | ||
|
||
# IPython | ||
profile_default/ | ||
ipython_config.py | ||
|
||
# pyenv | ||
# For a library or package, you might want to ignore these files since the code is | ||
# intended to run in multiple environments; otherwise, check them in: | ||
# .python-version | ||
|
||
# pipenv | ||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. | ||
# However, in case of collaboration, if having platform-specific dependencies or dependencies | ||
# having no cross-platform support, pipenv may install dependencies that don't work, or not | ||
# install all needed dependencies. | ||
#Pipfile.lock | ||
|
||
# poetry | ||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. | ||
# This is especially recommended for binary packages to ensure reproducibility, and is more | ||
# commonly ignored for libraries. | ||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control | ||
#poetry.lock | ||
|
||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow | ||
__pypackages__/ | ||
|
||
# Celery stuff | ||
celerybeat-schedule | ||
celerybeat.pid | ||
|
||
# SageMath parsed files | ||
*.sage.py | ||
|
||
# Environments | ||
.env | ||
.venv | ||
env/ | ||
venv/ | ||
ENV/ | ||
env.bak/ | ||
venv.bak/ | ||
|
||
# Spyder project settings | ||
.spyderproject | ||
.spyproject | ||
|
||
# Rope project settings | ||
.ropeproject | ||
|
||
# mkdocs documentation | ||
/site | ||
|
||
# mypy | ||
.mypy_cache/ | ||
.dmypy.json | ||
dmypy.json | ||
|
||
# Pyre type checker | ||
.pyre/ | ||
|
||
# pytype static type analyzer | ||
.pytype/ | ||
|
||
# Cython debug symbols | ||
cython_debug/ | ||
|
||
# PyCharm | ||
# JetBrains specific template is maintainted in a separate JetBrains.gitignore that can | ||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore | ||
# and can be added to the global gitignore or merged into this file. For a more nuclear | ||
# option (not recommended) you can uncomment the following to ignore the entire idea folder. | ||
#.idea/ | ||
|
||
# End of https://www.toptal.com/developers/gitignore/api/python | ||
.vscode/settings.json |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
# See https://pre-commit.com for more information | ||
# See https://pre-commit.com/hooks.html for more hooks | ||
repos: | ||
- repo: https://github.com/pre-commit/pre-commit-hooks | ||
rev: v3.2.0 | ||
hooks: | ||
- id: trailing-whitespace | ||
- id: end-of-file-fixer | ||
- id: check-yaml | ||
- id: check-added-large-files |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
# FastAPI Firebase integration | ||
|
||
This package contains some utilities to work with firebase in a FastAPI project. | ||
|
||
## Example usage | ||
|
||
For example, if you want to send the firebase app name: | ||
|
||
```python | ||
from fastapi import FastAPI, Depends | ||
from fastapi_firebase import setup_firebase, firebase_app | ||
from firebase_admin.app import App | ||
|
||
app=FastAPI() | ||
|
||
setup_firebase(app) | ||
|
||
@app.get("/appname") | ||
def get_appname(fb_app: App = Depends(firebase_app)): | ||
return fb_app.name | ||
|
||
``` | ||
|
||
See the `setup_firebase` documentation for how to initialize. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
"""A FastAPI integration for firebase. | ||
This package contains tools to use firebase services within a FastAPI application. | ||
The starting point is the app module because all other modules depend on it. | ||
""" | ||
from .app import firebase_app, setup_firebase | ||
|
||
__version__ = "0.1.0" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,120 @@ | ||
import typing | ||
import logging | ||
from fastapi import FastAPI | ||
from firebase_admin import App, credentials, delete_app, initialize_app | ||
|
||
log = logging.getLogger() | ||
|
||
|
||
class NotInitializedError(Exception): | ||
pass | ||
|
||
|
||
def _initialize_app( | ||
*, | ||
app_name: str = None, | ||
credentials_file: str = None, | ||
credentials_content: typing.Dict[str, typing.Any] = None, | ||
firebase_options: typing.Dict[str, typing.Any] = None, | ||
) -> App: | ||
"""Initialize the firebase application | ||
Args: | ||
app_name (str, optional): The app name to initialize. Defaults to None. | ||
credentials_file (str, optional): The credentials file path to use. Defaults to None. | ||
credentials_content (typing.Dict[str, typing.Any], optional): The credentials decoded | ||
content. Defaults to None. | ||
firebase_options (typing.Dict[str, typing.Any], optional): Additional firebase options. | ||
Defaults to None. | ||
Returns: | ||
App: The newly initialized app. | ||
Raises: | ||
ValueError: If any validation fails. | ||
""" | ||
|
||
kwargs = {} | ||
credential: credentials.Base = None | ||
if credentials_content: | ||
credential = credentials.Certificate(credentials_content) | ||
elif credentials_file: | ||
credential = credentials.Certificate(credentials_file) | ||
else: | ||
credential = credentials.ApplicationDefault() | ||
if credential: | ||
kwargs["credential"] = credential | ||
|
||
if app_name: | ||
kwargs["name"] = app_name | ||
|
||
if firebase_options: | ||
kwargs["options"] = firebase_options | ||
|
||
return initialize_app(**kwargs) | ||
|
||
|
||
def setup_firebase( | ||
app: FastAPI, | ||
credentials_file: str = None, | ||
credentials_content: typing.Dict[str, typing.Any] = None, | ||
firebase_options: typing.Dict[str, typing.Any] = None, | ||
): | ||
"""Add a firebase app to the FastAPI app. | ||
Args: | ||
app (FastAPI): The FastAPI app to attach to | ||
credentials_file (str, optional): The private certificate file to load. Defaults to None. | ||
credentials_content (typing.Dict[str, typing.Any], optional): The (already decoded) private | ||
key. Defaults to None. | ||
firebase_options (typing.Dict[str, typing.Any], optional): Additional firebase options. | ||
Defaults to None. | ||
""" | ||
_app: App = None | ||
|
||
@app.on_event("startup") | ||
def _setup_app(): | ||
nonlocal _app | ||
try: | ||
_app = _initialize_app( | ||
app_name=_app_name(app), | ||
credentials_content=credentials_content, | ||
credentials_file=credentials_file, | ||
firebase_options=firebase_options, | ||
) | ||
except Exception as ex: | ||
log.exception( | ||
"Error while trying to initialize the firebase SDK with provided args.", | ||
stack_info=True, | ||
exc_info=ex, | ||
) | ||
raise | ||
|
||
app.dependency_overrides[firebase_app] = lambda: _app | ||
log.info("Firebase sdk initialized and attached.") | ||
|
||
@app.on_event("shutdown") | ||
def _delete_app(): | ||
nonlocal _app | ||
del app.dependency_overrides[firebase_app] | ||
try: | ||
delete_app(_app) | ||
_app = None | ||
except Exception as ex: | ||
log.exception("Error while deleting the firebase app.", exc_info=ex) | ||
|
||
|
||
def firebase_app(): | ||
"""Return the initialized firebase app instance. | ||
Raises: | ||
NotInitializedError: If the firebase SDK is not initialized yet. | ||
Returns: | ||
App: The firebase app instance. | ||
""" | ||
raise NotInitializedError("The firebase application was not initialized.") | ||
|
||
|
||
def _app_name(app: FastAPI): | ||
return f"fb_app_{hash(app)}" |
Oops, something went wrong.