How to Protect your App with Simple Security Let’s build a small API Endpoint with FastAPI and protect it with SimpleSecurity.
API key based security package for FastAPI, focused on simplicity of use:
Full functionality out of the box, no configuration required API key security with local sqlite backend, working with both header and query parameters Default 15 days deprecation for generated API keys Key creation, revocation, renewing, and usage logs handled through administrator endpoints No dependencies, only requiring FastAPI and the python standard library Build new App and show the Directory Structure
Need a Litte Ping Function ? Test cat <<'EOF'> ping.py import argparse from ping3 import ping, verbose_ping def do_ping(host: str, timeout: int = 3, size: int = 1500, output: str = "json"): # output: json|txt # '21.54 ms' if size > 1500: size = 1500 result = ( str( round( ping(dest_addr=host, timeout=timeout, size=size, unit="ms"), 2, ) ) + " ms" ) if output.lower() == "json": return {"host": host, "timeout": timeout, "size": size, "result": result} if output.
a custom logger for Python let’s tune the default logger a bit so he write nice and colored messages.
Screenshot config.py a little config File …
cat <<'EOF'> config.py LOGGER_MAX_FILE_LENGTH = 10 EOF src/logger.py the logger code in the ‘src’ Folder
mkdir src cat <<'EOF'> src/logger.py import logging import datetime import sys from config import * if isinstance(LOGGER_MAX_FILE_LENGTH, int): LOGGER_MAX_FILE_LENGTH = str(LOGGER_MAX_FILE_LENGTH) def get_now() -> str: # # choose your format # current_time = datetime.
Flask & JWT getting your hands dirty with Flask and JWT
Source https://dev.to/grahammorby/jwt-auth-in-flask-python-18i4 with some modifications by myself …
Environment Test under macOS & OpenBSD, Poetry installed and working
Script build virtual env
export app="app100" export FLASK_APP="${app}/app" poetry new ${app} cd ${app} set python 3.10
poetry env use $(which python3.10) gsed -i "s/python = \"^3.*$/python = \"^3.10\"/" pyproject.toml poetry lock add packages
wget -4 -O requirements.txt https://raw.githubusercontent.com/GrahamMorbyDev/jwt-flask/master/requirements.txt echo "marshmallow-sqlalchemy" >> requirements.