Skip to main content

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.


Metadata

Release files for UnextPythonServiceUtils 0.1.15

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for UnextPythonServiceUtils 0.1.15
File Size Uploaded
unextpythonserviceutils-0.1.15.tar.gz 25.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for UnextPythonServiceUtils 0.1.15
File Interpreter ABI Platform
unextpythonserviceutils-0.1.15-py3-none-any.whl Python 3 none any Details

Total release size: 63.7 kB

Release files / unextpythonserviceutils-0.1.15.tar.gz

Download URL unextpythonserviceutils-0.1.15.tar.gz
Size 25.3 kB
Tags Source
SHA-256 checksum
How to use checksums
6665fafa82760659e8f53c443c98cc5f62e21b2682ece97bb05f95508d7131d7
BLAKE2b-256 checksum
How to use checksums
d4f979bf78b517d7ab94d7d6150ecda3272888dc6f9d1380fde76955a77e05ba
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.11.11

Release files / unextpythonserviceutils-0.1.15-py3-none-any.whl

Download URL unextpythonserviceutils-0.1.15-py3-none-any.whl
Size 38.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b7427cb0f9179430b28fd14ce1d5a992b33fc96c9a174fb778532c5884c787e8
BLAKE2b-256 checksum
How to use checksums
084e52f4647051430a287fc03fc4c5a42a052e5cb00bb6de66cd277876002d36
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.11.11

Release history Release notifications | RSS feed

This release

0.1.15 This release

2 release files

0.1.14

2 release files

0.1.13

2 release files

0.1.12

2 release files

0.1.11

2 release files

0.1.10

2 release files

0.1.9

2 release files

0.1.8

2 release files

0.1.6

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

0.0.9

2 release files

0.0.8

2 release files

0.0.7

2 release files

0.0.6

2 release files

0.0.5

2 release files

0.0.4

2 release files

0.0.3

2 release files

0.0.2

2 release files

0.0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page