Skip to content

Commit

Permalink
✨ fastapi-lazy Version 0.0.1 (#1)
Browse files Browse the repository at this point in the history
* Create 0.0.1

* Create a Setup File

* Create Dependencies

* Create a README

* Create Project workflows

* Fix Lint File
  • Loading branch information
yezz123 authored Sep 30, 2021
1 parent f525de4 commit 42593fc
Show file tree
Hide file tree
Showing 18 changed files with 418 additions and 2 deletions.
10 changes: 10 additions & 0 deletions .editorconfig
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
21 changes: 21 additions & 0 deletions .github/workflows/lint.yml
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
31 changes: 31 additions & 0 deletions .github/workflows/publish.yml
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
41 changes: 41 additions & 0 deletions .pre-commit-config.yaml
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"]
34 changes: 34 additions & 0 deletions Makefile
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
59 changes: 57 additions & 2 deletions README.md
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 🦥

[![Downloads](https://pepy.tech/badge/fastapi-lazy/month)](https://pepy.tech/project/fastapi-lazy)
[![PyPI version](https://badge.fury.io/py/fastapi-lazy.svg)](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.
8 changes: 8 additions & 0 deletions Setup.cfg
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}"
11 changes: 11 additions & 0 deletions fastapi-lazy/__init__.py
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"]
50 changes: 50 additions & 0 deletions fastapi-lazy/auth/auth.py
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,)
14 changes: 14 additions & 0 deletions fastapi-lazy/auth/model.py
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
23 changes: 23 additions & 0 deletions fastapi-lazy/database/mongo.py
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()
24 changes: 24 additions & 0 deletions fastapi-lazy/database/psql.py
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()
43 changes: 43 additions & 0 deletions fastapi-lazy/database/redis.py
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)
14 changes: 14 additions & 0 deletions fastapi-lazy/generator/generator.py
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 added fastapi-lazy/py.typed
Empty file.
Loading

0 comments on commit 42593fc

Please sign in to comment.