Skip to main content

A most utile package for the governance of pythonic micro-services

Project description

PythonServiceUtil

PythonServiceUtil is a utility library designed to streamline Python-based microservice development. It offers robust support for:

  • REST Inter-service Calls: Simplifies HTTP communication between services.
  • AWS SQS Integration: Enhances message queue operations.
  • Redis Support: Provides efficient caching and data storage.
  • MongoDB Integration: Simplifies database interactions, including transactions (mongoengine object data mapper).
  • Context Management: Facilitates seamless context management in multithreaded and multiprocessing environments.

Features

Validation Workflow

The validation process is structured as follows:

  1. Access Token Validation: Validates the access token as the primary step.
  2. Fallback to X-API-KEY Validation: If the access token validation fails, X-API-KEY validation is used as a fallback.

Note: The JWKS (JSON Web Key Set) must follow the format List[Jwk_TH]. Specify the symmetric or asymmetric algorithm to use via AUTH_TOKEN_ALGORITHM.

class Jwk_TH(TypedDict, total=False):
    alg: Required[str]
    e: str
    kid: Required[str]
    kty: str
    n: str
    use: str

def __load_jwks() -> List[Jwk_TH]:
    return json.loads(str(config("JWKS")))

Configuration

Configure the library using an .env file with the following keys:

ENVIRONMENT=develop
LOGGING_FILENAME=service.log
AUTH_TOKEN_ALGORITHM=RS256
BEDROCK_AWS_REGION_NAME=region_name
AWS_REGION_NAME=region_name
AWS_ACCESS_KEY=your_access_key
AWS_SECRET_ACCESS_KEY=your_secret_access_key
X_API_KEY_EMBEDDING_SERVICE_1=access_key
X_API_KEY_EMBEDDING_SERVICE_2=access_key
JWKS=JWKS

Usage

Headers Validation Model

The headers validation model supports both inter-service calls and client-to-backend communication. It first checks cookie validation and then falls back to header-based authorization.

import uuid
from pydantic import BaseModel, Field
from typing import Any, Dict

class Headers_PM(BaseModel):
    correlationid: str = Field(default_factory=lambda: str(uuid.uuid4()))
    username: str = "not_applicable"
    authorization: str = Field(default="")

    def model_dump(self, exclude_fields={}, **kwargs) -> Dict[str, Any]:
        return super().model_dump(**kwargs, exclude=exclude_fields)

Setting Up REST Middlewares

Here is an example of setting up REST middlewares in a FastAPI app:

app.add_middleware(
    HeaderValidationMiddleware,
    x_api_key_1=cast(str, config("X_API_KEY_EMBEDDING_SERVICE_1")),
    x_api_key_2=cast(str, config("X_API_KEY_EMBEDDING_SERVICE_2")),
    authexpiryignore_paths=frozenset([
        ServicePaths.CONTEXT_PATH.value + "/encoders",
        ServicePaths.CONTEXT_PATH.value + "/llm",
    ]),
)
app.add_middleware(ExceptionMiddleware)

Key Fields in Headers_PM

  • correlationid: A unique identifier for tracing requests, generated using uuid4().
  • username: The username associated with the request; defaults to "not_applicable".
  • authorization: The authorization token, defaulting to an empty string.

License

This project is licensed under the MIT License. See the LICENSE file for details.


Contributing

Contributions are welcome! Follow these steps:

  1. Fork the repository.
  2. Create a feature branch: git checkout -b feature-name.
  3. Commit your changes: git commit -m 'Add feature'.
  4. Push to the branch: git push origin feature-name.
  5. Open a pull request.

Publishing to PyPI

To upload the library to PyPI, follow these steps:

pip install -r requirements.dev.txt
python setup.py bdist_wheel sdist
twine check dist/*
twine upload dist/*

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

zoldics_service_utils-0.1.12.tar.gz (25.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

zoldics_service_utils-0.1.12-py3-none-any.whl (38.3 kB view details)

Uploaded Python 3

File details

Details for the file zoldics_service_utils-0.1.12.tar.gz.

File metadata

  • Download URL: zoldics_service_utils-0.1.12.tar.gz
  • Upload date:
  • Size: 25.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.11.11

File hashes

Hashes for zoldics_service_utils-0.1.12.tar.gz
Algorithm Hash digest
SHA256 d6aa7874c51d7030efdd43a5886f72c60686c86e904904fb749a970e85dfb33d
MD5 81dafc2e5d0fa60cb64f72ef982a037b
BLAKE2b-256 1b9a17e906f34d891ad85fe0a562c086f833ef05cf01babe7887347ded62f48f

See more details on using hashes here.

File details

Details for the file zoldics_service_utils-0.1.12-py3-none-any.whl.

File metadata

File hashes

Hashes for zoldics_service_utils-0.1.12-py3-none-any.whl
Algorithm Hash digest
SHA256 194a69b60a0e547e01769c0db5e2be4c2f2a3aaf8cd65842c822d286595f296e
MD5 d8377959e9059014e5c67d18f48d732b
BLAKE2b-256 eb1e90ebf5f7700dc7a42f73be67ba7fdcfa2dda542452c65eaa9e91d4e1869d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page