Skip to content

code4mk/fastapi-pundra

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

24 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

FastAPI Pundra

PyPI version Python 3.10+ License: MIT

Pundra: Your FastAPI Companion for Productivity

FastAPI Pundra is a comprehensive toolkit that extends FastAPI with essential utilities, helpers, and integrations to accelerate your API development. Whether you're building REST APIs or GraphQL endpoints, Pundra provides the building blocks you need to create robust, scalable applications.

πŸš€ Features

πŸ”§ Common Utilities

  • Password Management: Secure password hashing and verification using bcrypt
  • JWT Utilities: Token generation and validation helpers
  • Raw SQL Support: Execute raw SQL queries with ease
  • Helper Functions: Common utility functions for path management and more

πŸ“§ Email System

  • Template-based Emails: HTML email templates with inline CSS support
  • Background Email Tasks: Asynchronous email sending with Celery integration
  • Mail Queue Management: Reliable email delivery with queue support
  • Multiple Recipients: Support for CC, BCC, and reply-to functionality

πŸ”„ Task Scheduling

  • Celery Integration: Seamless Celery setup and configuration
  • Cron Scheduling: Define and manage scheduled tasks
  • Beat Scheduler: Redis-based beat scheduler for reliable task execution
  • Dynamic Task Discovery: Automatic task module discovery

🌐 REST API Enhancements

  • Exception Handling: Comprehensive exception classes for different HTTP status codes
  • Global Exception Handler: Centralized error handling for your FastAPI app
  • Pagination: Built-in pagination with URL generation
  • Validation Helpers: Enhanced request validation utilities

πŸ“ GraphQL Support (Strawberry)

  • Common GraphQL Types: Reusable GraphQL type definitions
  • Pagination Types: Generic paginated list types for GraphQL
  • Resolver Utilities: Helper functions for Strawberry resolvers
  • Validation Integration: GraphQL-specific validation helpers

πŸ“¦ Installation

pip install fastapi-pundra

πŸ› οΈ Quick Start

Basic Setup

from fastapi import FastAPI
from fastapi_pundra.rest.global_exception_handler import setup_exception_handlers
from fastapi_pundra.common.password import generate_password_hash, compare_hashed_password

app = FastAPI()

# Setup global exception handling
setup_exception_handlers(app)

@app.get("/")
async def root():
    return {"message": "Hello from FastAPI Pundra!"}

Password Management

from fastapi_pundra.common.password import generate_password_hash, compare_hashed_password

# Hash a password
password = "my_secure_password"
hashed = generate_password_hash(password)

# Verify a password
is_valid = compare_hashed_password(password, hashed)
print(is_valid)  # True

Email Sending

from fastapi import BackgroundTasks
from fastapi_pundra.common.mailer.mail import send_mail, send_mail_background

# Send email directly
await send_mail(
    subject="Welcome!",
    to=["user@example.com"],
    template_name="welcome_email.html",
    context={"username": "John Doe"}
)

# Send email in background
async def send_welcome_email(background_tasks: BackgroundTasks):
    await send_mail_background(
        background_tasks=background_tasks,
        subject="Welcome!",
        to=["user@example.com"],
        template_name="welcome_email.html",
        context={"username": "John Doe"}
    )

Pagination

from fastapi import Request
from fastapi_pundra.rest.paginate import paginate

@app.get("/users")
async def get_users(request: Request):
    # Assuming you have a SQLAlchemy query
    query = session.query(User)
    return paginate(
        request=request,
        query=query,
        serilizer=UserSerializer,
        the_page=1,
        the_per_page=10
    )

Celery Task Scheduling

from fastapi_pundra.common.scheduler.celery import create_celery_app

# Create Celery app
celery_app = create_celery_app("my_project")

@celery_app.task
def my_scheduled_task():
    print("This task runs on schedule!")
    return "Task completed"

GraphQL with Strawberry

import strawberry
from fastapi_pundra.gql_berry.common_gql_type import PaginatedList

@strawberry.type
class User:
    id: int
    name: str
    email: str

@strawberry.type
class Query:
    @strawberry.field
    def users(self) -> PaginatedList[User]:
        # Your logic here
        return PaginatedList(
            data=[User(id=1, name="John", email="john@example.com")],
            pagination={"page": 1, "total": 1}
        )

πŸ”§ Configuration

Environment Variables

Create a .env file with the following variables:

# Email Configuration
MAIL_USERNAME=your_email@gmail.com
MAIL_PASSWORD=your_app_password
MAIL_FROM_ADDRESS=noreply@yourdomain.com
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_SSL_TLS=True
MAIL_STARTTLS=False
MAIL_USE_CREDENTIALS=True

# Celery Configuration
CELERY_BROKER_URL=redis://localhost:6379/0
CELERY_RESULT_BACKEND=redis://localhost:6379/0

# Project Configuration
PROJECT_BASE_PATH=app

πŸ“ Project Structure

fastapi-pundra/
β”œβ”€β”€ common/                 # Common utilities
β”‚   β”œβ”€β”€ helpers.py         # Helper functions
β”‚   β”œβ”€β”€ jwt_utils.py       # JWT utilities
β”‚   β”œβ”€β”€ password.py        # Password management
β”‚   β”œβ”€β”€ mailer/            # Email system
β”‚   β”‚   β”œβ”€β”€ mail.py        # Email sending
β”‚   β”‚   β”œβ”€β”€ mail_queue.py  # Email queue
β”‚   β”‚   └── ...
β”‚   β”œβ”€β”€ raw_sql/           # Raw SQL utilities
β”‚   └── scheduler/         # Task scheduling
β”œβ”€β”€ rest/                  # REST API utilities
β”‚   β”œβ”€β”€ exceptions.py      # Exception classes
β”‚   β”œβ”€β”€ paginate.py        # Pagination
β”‚   └── ...
└── gql_berry/            # GraphQL utilities
    β”œβ”€β”€ common_gql_type.py # GraphQL types
    β”œβ”€β”€ pagination.py      # GraphQL pagination
    └── ...

πŸ§ͺ Testing

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

πŸ“š Documentation

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“„ License

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

πŸ‘¨β€πŸ’» Author

Mostafa Kamal

πŸ™ Acknowledgments

πŸ“ˆ Roadmap

  • Add more GraphQL utilities
  • Enhanced caching support
  • Database migration helpers
  • API rate limiting
  • WebSocket utilities
  • Enhanced logging system

Made with ❀️ for the FastAPI community

About

Pundra: Your FastAPI Companion for Productivity

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published