Skip to main content

Shared utilities and models for Agrifrika microservices

Project description

Agrifrika Shared Package

Shared utilities, models, and AWS clients for all Agrifrika microservices.

Features

  • Response Builders: Standardized API response formatting
  • Request Parsers: Lambda event parsing with Pydantic validation
  • Structured Logging: JSON-formatted logs for CloudWatch Logs Insights
  • AWS Clients: Singleton boto3 clients with retry logic
  • DynamoDB Client: High-level DynamoDB operations wrapper
  • Cognito Client: User management operations wrapper
  • Exception Classes: Custom business and validation exceptions
  • Validators: Common validation utilities (email, phone, etc.)

Installation

Development Installation (Editable Mode)

For local development, install in editable mode so changes are reflected immediately:

cd agrifrika-backend/shared
pip install -e .

Production Installation

pip install agrifrika-shared

With Development Dependencies

pip install -e ".[dev]"

Usage

Response Builders

from agrifrika_shared.utils.response_builder import success_response, error_response

# Success response
return success_response({"user_id": "123"}, "User created successfully", 201)

# Error response
return error_response("User not found", 404, error_code="USER_NOT_FOUND")

Request Parsing

from agrifrika_shared.utils.request_parser import parse_lambda_event
from pydantic import BaseModel

class CreateUserRequest(BaseModel):
    email: str
    name: str

def handler(event, context):
    # Automatically parse and validate
    request = parse_lambda_event(event, CreateUserRequest)
    print(request.email)  # Validated email

Structured Logging

from agrifrika_shared.utils.logger import get_logger

logger = get_logger(__name__)

logger.info("user_created", user_id="123", email="test@example.com")
# Output: {"timestamp": "2025-01-15T10:30:00Z", "level": "INFO", "message": "user_created", ...}

AWS Clients

from agrifrika_shared.aws.clients import get_dynamodb_resource, get_cognito_client

# DynamoDB
dynamodb = get_dynamodb_resource()
table = dynamodb.Table('users')

# Cognito
cognito = get_cognito_client()
response = cognito.admin_get_user(UserPoolId='...', Username='...')

DynamoDB Client

from agrifrika_shared.aws.dynamo_client import DynamoDBClient

client = DynamoDBClient()

# Put item
client.put_item('users', {'id': '123', 'name': 'John'})

# Get item
user = client.get_item('users', {'id': '123'})

# Query
from boto3.dynamodb.conditions import Key
result = client.query('users', Key('status').eq('active'), index_name='StatusIndex')

Cognito Client

from agrifrika_shared.aws.cognito_client import CognitoClient

client = CognitoClient()

# Create user
user = client.create_user(
    'test@example.com',
    'TempPass123!',
    attributes={'given_name': 'John', 'family_name': 'Doe'}
)

# Add to group
client.add_user_to_group('test@example.com', 'Admins')

Custom Exceptions

from agrifrika_shared.utils.exceptions import NotFoundError, ValidationError

# Raise exceptions
if not user:
    raise NotFoundError('User', user_id)

if not validate_email(email):
    raise ValidationError('Invalid email format', field='email')

Project Structure

agrifrika_shared/
├── __init__.py
├── models/              # Pydantic models (to be added)
│   ├── __init__.py
│   ├── base.py
│   ├── user.py
│   └── ...
├── utils/               # Utility functions
│   ├── __init__.py
│   ├── request_parser.py
│   ├── response_builder.py
│   ├── logger.py
│   ├── exceptions.py
│   └── validators.py
├── aws/                 # AWS client wrappers
│   ├── __init__.py
│   ├── clients.py
│   ├── dynamo_client.py
│   └── cognito_client.py
└── config/              # Configuration
    ├── __init__.py
    └── settings.py

Development

Running Tests

pytest

Running Tests with Coverage

pytest --cov=agrifrika_shared --cov-report=html

Code Formatting

# Format with black
black agrifrika_shared/

# Sort imports
isort agrifrika_shared/

# Lint with ruff
ruff check agrifrika_shared/

Type Checking

mypy agrifrika_shared/ --strict

Integration with Services

To use the shared package in a service:

  1. Add to requirements.txt:

    -e ../../../shared
    boto3==1.28.0
    pydantic==2.5.0
    
  2. Install dependencies:

    cd services/aggregator_service
    pip install -r requirements.txt
    
  3. Import and use:

    from agrifrika_shared.utils import success_response, parse_lambda_event
    from agrifrika_shared.aws.dynamo_client import DynamoDBClient
    

Environment Variables

The shared package uses the following environment variables:

  • AWS_REGION: AWS region (default: us-east-1)
  • COGNITO_USER_POOL_ID: Cognito user pool ID (required for CognitoClient)
  • LOG_LEVEL: Logging level (default: INFO)

Contributing

  1. Make changes to the shared package
  2. Add tests for new functionality
  3. Run tests and linting
  4. Update this README if adding new features

License

MIT

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

agrifrika_shared-0.3.6.tar.gz (33.0 kB view details)

Uploaded Source

Built Distribution

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

agrifrika_shared-0.3.6-py3-none-any.whl (39.1 kB view details)

Uploaded Python 3

File details

Details for the file agrifrika_shared-0.3.6.tar.gz.

File metadata

  • Download URL: agrifrika_shared-0.3.6.tar.gz
  • Upload date:
  • Size: 33.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.25

File hashes

Hashes for agrifrika_shared-0.3.6.tar.gz
Algorithm Hash digest
SHA256 a9612eba5e40f866af4fcb81cdab966d2e125d4cf3ccc58b6d5b5ea12a95fcb3
MD5 4097f6e8c47d19b0c9dca0fe09a67cef
BLAKE2b-256 dc74a7edf3edea4c233ea61254b1b5df188ffce19ed3b1a3958efc29fa23409f

See more details on using hashes here.

File details

Details for the file agrifrika_shared-0.3.6-py3-none-any.whl.

File metadata

File hashes

Hashes for agrifrika_shared-0.3.6-py3-none-any.whl
Algorithm Hash digest
SHA256 9ed3b3c07e282f7f69775bb13f8d02597a646de7b618bf3da95bd67b7eb9429d
MD5 77aa7e4e855ed5fc7cffd5fd98fd5946
BLAKE2b-256 4f7a08d837ede8adbbae21dbcb3dea8ed76d9c5df8a2479cb39cdfb3f1dbaa42

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