-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Create 0.0.1 * Create a Setup File * Create Dependencies * Create a README * Create Project workflows * Fix Lint File
- Loading branch information
Showing
18 changed files
with
418 additions
and
2 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,10 @@ | ||
# top-most EditorConfig file | ||
root = true | ||
|
||
[*] | ||
indent_style = space | ||
indent_size = 4 | ||
end_of_line = lf | ||
charset = utf-8 | ||
trim_trailing_whitespace = false | ||
insert_final_newline = false |
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,21 @@ | ||
name: Test Project Linting | ||
|
||
on: [push, pull_request] | ||
|
||
jobs: | ||
deploy: | ||
runs-on: ubuntu-latest | ||
|
||
steps: | ||
- uses: actions/checkout@v2 | ||
- name: Set up Python | ||
uses: actions/setup-python@v2 | ||
with: | ||
python-version: "3.9" | ||
- name: Install dependencies | ||
run: | | ||
python -m pip install --upgrade pip | ||
make install | ||
- name: Test Project linting | ||
run: | | ||
make lint |
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,31 @@ | ||
name: Upload Python Package | ||
|
||
on: | ||
release: | ||
types: [published] | ||
|
||
jobs: | ||
deploy: | ||
runs-on: ubuntu-latest | ||
|
||
steps: | ||
- uses: actions/checkout@v2 | ||
- name: Set up Python | ||
uses: actions/setup-python@v2 | ||
with: | ||
python-version: "3.9" | ||
- name: Install dependencies | ||
run: | | ||
python -m pip install --upgrade pip | ||
make install | ||
make setuptools | ||
- name: Test Project linting | ||
run: | | ||
make lint | ||
- name: Build and publish | ||
env: | ||
TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} | ||
TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} | ||
run: | | ||
make build | ||
make publish |
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,41 @@ | ||
default_language_version: | ||
python: python3.9 | ||
repos: | ||
- repo: https://github.com/pre-commit/pre-commit-hooks | ||
rev: v2.2.3 | ||
hooks: | ||
- id: check-merge-conflict | ||
- id: check-added-large-files | ||
- id: check-ast | ||
- id: check-symlinks | ||
- id: check-yaml | ||
- id: trailing-whitespace | ||
- id: check-json | ||
- id: debug-statements | ||
- id: pretty-format-json | ||
args: ["--autofix", "--allow-missing-credentials"] | ||
- repo: https://github.com/PyCQA/isort | ||
rev: 5.6.4 | ||
hooks: | ||
- id: isort | ||
args: ["--profile", "black"] | ||
- repo: https://gitlab.com/pycqa/flake8 | ||
rev: "8f9b4931b9a28896fb43edccb23016a7540f5b82" | ||
hooks: | ||
- id: flake8 | ||
additional_dependencies: [flake8-print] | ||
files: '\.py$' | ||
args: | ||
- --select=F403,F406,F821,T003 | ||
- repo: https://github.com/humitos/mirrors-autoflake | ||
rev: v1.3 | ||
hooks: | ||
- id: autoflake | ||
files: '\.py$' | ||
exclude: '^\..*' | ||
args: ["--in-place"] | ||
- repo: https://github.com/psf/black | ||
rev: 19.10b0 | ||
hooks: | ||
- id: black | ||
args: ["--target-version", "py38"] |
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,34 @@ | ||
help: | ||
@echo "Targets:" | ||
@echo " make setuptools" | ||
@echo " make install" | ||
@echo " make build" | ||
@echo " make lint" | ||
@echo " make publish" | ||
@echo " make bumpversion-major" | ||
@echo " make bumpversion-minor" | ||
@echo " make bumpversion-patch" | ||
|
||
setuptools: | ||
pip install setuptools wheel twine | ||
|
||
install: | ||
pip install -r requirements.dev.txt | ||
|
||
lint: | ||
pre-commit run --all-files | ||
|
||
build: | ||
python setup.py sdist bdist_wheel | ||
|
||
publish: | ||
twine upload dist/* | ||
|
||
bumpversion-major: | ||
bumpversion major --allow-dirty | ||
|
||
bumpversion-minor: | ||
bumpversion minor | ||
|
||
bumpversion-patch: | ||
bumpversion patch |
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 |
---|---|---|
@@ -1,2 +1,57 @@ | ||
# fastapi-lazy | ||
A Lazy package to start you project ✨ | ||
# Fastapi-lazy 🦥 | ||
|
||
[](https://pepy.tech/project/fastapi-lazy) | ||
[](https://badge.fury.io/py/fastapi-lazy) | ||
|
||
Utilities that you use in various projects made in FastAPI. | ||
|
||
--- | ||
|
||
**Source Code**: <https://github.com/yezz123/fastapi-lazy> | ||
|
||
**Install the project**: `pip install fastapi-lazy` | ||
|
||
--- | ||
|
||
## Features 🎉 | ||
|
||
- Use the data contained in the JWT | ||
- Use the username contained in the JWT and fetch data. | ||
- Multi Database Support: | ||
- Creates the dependency to be used to connect to the Postgresql. | ||
- Creates the dependency to be used to connect to the MongoDB. | ||
- Support Redis Cache: | ||
- Creates a `pickle` of the object passed as a parameter and saves it in the Redis which is also passed as a parameter. | ||
- Read the `pickle` of the object saved in RedisDB and return it as Python object. | ||
- Support UUID generator: | ||
- Create a custom UUID4 using the current timestamp. | ||
|
||
## Development 🚧 | ||
|
||
You should create a virtual environment and activate it: | ||
|
||
```bash | ||
python -m venv venv/ | ||
``` | ||
|
||
```bash | ||
source venv/bin/activate | ||
``` | ||
|
||
And then install the development dependencies: | ||
|
||
```bash | ||
pip install -r requirements.dev.txt | ||
``` | ||
|
||
### Format the code 💅 | ||
|
||
Execute the following command to apply `pre-commit` formatting: | ||
|
||
```bash | ||
make lint | ||
``` | ||
|
||
## License 🍻 | ||
|
||
This project is licensed under the terms of the MIT license. |
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,8 @@ | ||
[bumpversion] | ||
current_version = 0.0.1 | ||
commit = True | ||
tag = True | ||
|
||
[bumpversion:file:fastapi-lazy/__init__.py] | ||
search = __version__ = "{current_version}" | ||
replace = __version__ = "{new_version}" |
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,11 @@ | ||
__version__ = "0.0.1" | ||
|
||
""" | ||
fastapi-lazy - A Lazy package-starter for FastAPI applications. | ||
""" | ||
|
||
from auth import auth, model | ||
from database import mongo, psql, redis | ||
from generator import generator | ||
|
||
__all__ = ["auth", "model", "mongo", "redis", "psql", "generator"] |
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,50 @@ | ||
from os import environ | ||
|
||
from auth.model import LazyUser | ||
from fastapi.exceptions import HTTPException | ||
from fastapi.security import HTTPBearer | ||
from jwt import decode | ||
from starlette.requests import Request | ||
from starlette.status import HTTP_403_FORBIDDEN | ||
|
||
KEY = environ.get("KEY", "secret") | ||
|
||
|
||
class LazyAuth(HTTPBearer): | ||
""" | ||
A custom authentication class that uses the JWT token to authenticate the user. | ||
Args: | ||
HTTPBearer (class): The class that handles the authentication. | ||
""" | ||
|
||
async def __call__(self, request: Request) -> LazyUser: | ||
""" | ||
The authentication method. | ||
Args: | ||
request (Request): The request object. | ||
Raises: | ||
HTTPException: If the token is invalid. | ||
Returns: | ||
LazyUser: The user object. | ||
""" | ||
cred = await super().__call__(request) | ||
try: | ||
user = decode(cred.credentials, key=KEY, algorithms="HS256") | ||
except Exception as exp: | ||
""" | ||
If the token is invalid, raise an HTTPException. | ||
Raises: | ||
HTTPException: If the token is invalid. | ||
""" | ||
raise HTTPException( | ||
status_code=HTTP_403_FORBIDDEN, detail=str(exp), | ||
) | ||
return LazyUser(**user) | ||
|
||
|
||
authentication_lazy = LazyAuth(scheme_name="Bearer", auto_error=False,) |
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,14 @@ | ||
from pydantic import BaseModel | ||
|
||
|
||
class LazyUser(BaseModel): | ||
""" | ||
A lazy user model. | ||
Args: | ||
BaseModel (pydantic.BaseModel): Base model class. | ||
""" | ||
|
||
username: str | ||
password: str | ||
role: str |
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,23 @@ | ||
from os import environ | ||
|
||
from motor.motor_asyncio import AsyncIOMotorClient | ||
|
||
link = f'mongodb://{environ["MONGO_USER"]}:{environ["MONGO_PASSWORD"]}@mongo:27017/' | ||
|
||
# MongoDB | ||
async def get_mongo() -> AsyncIOMotorClient: | ||
""" | ||
Get MongoDB client | ||
Returns: | ||
AsyncIOMotorClient: MongoDB client | ||
Yields: | ||
Iterator[AsyncIOMotorClient]: MongoDB client | ||
""" | ||
client = AsyncIOMotorClient(link) | ||
database = client.fastapi_lazy | ||
try: | ||
yield database | ||
finally: | ||
await database.close() |
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 @@ | ||
from os import environ | ||
|
||
from databases import Database | ||
|
||
link = f"postgresql://{environ['DB_USER']}:{environ['DB_PASSWORD']}@{environ['DB_HOST']}:{environ['DB_PORT']}/{environ['DB_NAME']}" | ||
|
||
|
||
# Postgresql | ||
async def get_psql() -> Database: | ||
""" | ||
Get Postgresql database connection | ||
Returns: | ||
Database: Postgresql database connection | ||
Yields: | ||
Iterator[Database]: Postgresql database connection | ||
""" | ||
db = Database(link) | ||
await db.connect() | ||
try: | ||
yield db | ||
finally: | ||
await db.disconnect() |
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,43 @@ | ||
import logging | ||
import pickle | ||
|
||
log = logging.getLogger(__name__) | ||
|
||
# Get from redis | ||
async def get_from_redis(redis, key: str): | ||
""" | ||
Get data from redis | ||
Args: | ||
redis (redis.Redis): Redis client | ||
key (str): Key of data | ||
Returns: | ||
dict: Data | ||
""" | ||
try: | ||
value = await redis.get(key) | ||
if value: | ||
return pickle.loads(value) | ||
except Exception as exp: | ||
log.error("Error relate to Redis ", exp) | ||
|
||
|
||
# Set to redis | ||
async def set_to_redis(redis, name: str, value: dict, idd: int): | ||
""" | ||
Set data to redis | ||
Args: | ||
redis (redis.Redis): Redis client | ||
name (str): Name of data | ||
value (dict): Data | ||
idd (int): Id of data | ||
Returns: | ||
bool: True if success, False if fail | ||
""" | ||
try: | ||
await redis.set(name, pickle.dumps(value), idd=idd) | ||
except Exception as exp: | ||
log.error("Error setting redis: ", exp) |
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,14 @@ | ||
from datetime import datetime | ||
from math import ceil | ||
from random import getrandbits | ||
|
||
""" | ||
generate a uuid with the following format | ||
""" | ||
|
||
|
||
def gen_uuid() -> str: | ||
bytes = ( | ||
hex(ceil(datetime.utcnow().timestamp() * 1000))[2:] + hex(getrandbits(96))[2:] | ||
)[:32] | ||
return f"{bytes[:8]}-{bytes[8:12]}-4{bytes[13:16]}-{bytes[16:19]}9-{bytes[20:32]}" |
Empty file.
Oops, something went wrong.