UNPKG

@re-shell/cli

Version:

Full-stack development platform uniting microservices and microfrontends. Build complete applications with .NET (ASP.NET Core Web API, Minimal API), Java (Spring Boot, Quarkus, Micronaut, Vert.x), Rust (Actix-Web, Warp, Rocket, Axum), Python (FastAPI, Dja

1,546 lines (1,239 loc) 102 kB
"use strict"; /** * Comprehensive Type Hints Generator for Python Framework Templates * Provides modern typing annotations for FastAPI, Django, Flask, Tornado, and Sanic */ Object.defineProperty(exports, "__esModule", { value: true }); exports.pythonTypeHintsGenerator = exports.PythonTypeHintsGenerator = void 0; class PythonTypeHintsGenerator { generateTypeHintsConfig(framework) { return { framework, pythonVersion: '3.11', strictMode: true, enableDataclasses: true, enablePydantic: true, enableProtocols: true, enableGenericAliases: true }; } generateBaseTypes() { return `""" Base type definitions for Python applications Provides comprehensive typing support for all frameworks """ from __future__ import annotations import sys from typing import ( TYPE_CHECKING, Any, Awaitable, Callable, ClassVar, Dict, Generic, List, Literal, Optional, Protocol, Tuple, Type, TypeVar, Union, overload, ) if sys.version_info >= (3, 10): from typing import ParamSpec, TypeGuard, TypeAlias else: from typing_extensions import ParamSpec, TypeGuard, TypeAlias if sys.version_info >= (3, 11): from typing import NotRequired, Required, Self else: from typing_extensions import NotRequired, Required, Self from datetime import datetime, date, time from decimal import Decimal from pathlib import Path from uuid import UUID import json # Type Variables T = TypeVar('T') K = TypeVar('K') V = TypeVar('V') P = ParamSpec('P') # Common Type Aliases JSONValue: TypeAlias = Union[str, int, float, bool, None, Dict[str, Any], List[Any]] JSONDict: TypeAlias = Dict[str, JSONValue] JSONList: TypeAlias = List[JSONValue] # Path Types PathLike: TypeAlias = Union[str, Path] FilePath: TypeAlias = Union[str, Path] DirectoryPath: TypeAlias = Union[str, Path] # Database Types DatabaseURL: TypeAlias = str ConnectionString: TypeAlias = str QueryParams: TypeAlias = Dict[str, Any] # HTTP Types HTTPMethod: TypeAlias = Literal['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] HTTPStatus: TypeAlias = int HTTPHeaders: TypeAlias = Dict[str, str] HTTPParams: TypeAlias = Dict[str, Union[str, int, float, bool]] # Response Types StatusCode: TypeAlias = int ResponseData: TypeAlias = Union[Dict[str, Any], List[Any], str, int, float, bool, None] # Authentication Types UserID: TypeAlias = Union[str, int, UUID] Token: TypeAlias = str ApiKey: TypeAlias = str # Validation Types ValidationError: TypeAlias = Dict[str, List[str]] FieldErrors: TypeAlias = Dict[str, str] # Configuration Types ConfigValue: TypeAlias = Union[str, int, float, bool, None] ConfigDict: TypeAlias = Dict[str, ConfigValue] EnvironmentVar: TypeAlias = str # Async Types AsyncCallable: TypeAlias = Callable[..., Awaitable[Any]] AsyncGenerator: TypeAlias = Callable[..., Any] # AsyncGenerator type # Generic Protocol Definitions class Serializable(Protocol): """Protocol for objects that can be serialized to JSON.""" def to_dict(self) -> Dict[str, Any]: ... @classmethod def from_dict(cls, data: Dict[str, Any]) -> Self: ... class Identifiable(Protocol[T]): """Protocol for objects with an ID.""" id: T class Timestamped(Protocol): """Protocol for objects with timestamp fields.""" created_at: datetime updated_at: Optional[datetime] class Validatable(Protocol): """Protocol for objects that can be validated.""" def validate(self) -> bool: ... def get_errors(self) -> ValidationError: ... class Cacheable(Protocol[K, V]): """Protocol for cacheable objects.""" def get_cache_key(self) -> K: ... def get_cache_value(self) -> V: ... def get_cache_ttl(self) -> Optional[int]: ... # Framework-specific protocols class RequestHandler(Protocol): """Generic request handler protocol.""" def handle_request(self, request: Any) -> Awaitable[Any]: ... class Middleware(Protocol): """Generic middleware protocol.""" def process_request(self, request: Any) -> Any: ... def process_response(self, response: Any) -> Any: ... class DatabaseConnection(Protocol): """Generic database connection protocol.""" async def execute(self, query: str, params: Optional[QueryParams] = None) -> Any: ... async def fetch_one(self, query: str, params: Optional[QueryParams] = None) -> Optional[Dict[str, Any]]: ... async def fetch_all(self, query: str, params: Optional[QueryParams] = None) -> List[Dict[str, Any]]: ... # Type Guards def is_json_dict(value: Any) -> TypeGuard[JSONDict]: """Type guard for JSON dictionary.""" return isinstance(value, dict) and all( isinstance(k, str) for k in value.keys() ) def is_valid_id(value: Any) -> TypeGuard[Union[str, int, UUID]]: """Type guard for valid ID types.""" return isinstance(value, (str, int, UUID)) def is_http_method(value: str) -> TypeGuard[HTTPMethod]: """Type guard for HTTP methods.""" return value.upper() in {'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'} # Utility type functions def ensure_list(value: Union[T, List[T]]) -> List[T]: """Ensure value is a list.""" return value if isinstance(value, list) else [value] def ensure_dict(value: Union[Dict[K, V], List[Tuple[K, V]]]) -> Dict[K, V]: """Ensure value is a dictionary.""" return value if isinstance(value, dict) else dict(value) # Generic Result Types class Result(Generic[T]): """Generic result type for operations that can fail.""" def __init__(self, value: Optional[T] = None, error: Optional[str] = None): self._value = value self._error = error @property def is_success(self) -> bool: return self._error is None @property def is_error(self) -> bool: return self._error is not None @property def value(self) -> T: if self._error is not None: raise ValueError(f"Result has error: {self._error}") return self._value # type: ignore @property def error(self) -> Optional[str]: return self._error @classmethod def success(cls, value: T) -> Result[T]: return cls(value=value) @classmethod def failure(cls, error: str) -> Result[T]: return cls(error=error) # Pagination Types class PaginationInfo(Protocol): """Pagination information protocol.""" page: int limit: int total: int pages: int has_next: bool has_prev: bool class PaginatedResponse(Generic[T], Protocol): """Paginated response protocol.""" data: List[T] pagination: PaginationInfo `; } generateFastAPITypes() { return `""" FastAPI-specific type definitions Enhanced typing support for FastAPI applications """ from __future__ import annotations from typing import ( Any, Awaitable, Callable, Dict, List, Optional, Union, get_type_hints, ) from fastapi import FastAPI, Request, Response, Depends, HTTPException from fastapi.routing import APIRoute from fastapi.security import HTTPBearer, OAuth2PasswordBearer from pydantic import BaseModel, Field from starlette.middleware.base import BaseHTTPMiddleware from starlette.responses import JSONResponse # FastAPI Application Types FastAPIApp: TypeAlias = FastAPI FastAPIRequest: TypeAlias = Request FastAPIResponse: TypeAlias = Response # Dependency Types Dependency: TypeAlias = Callable[..., Any] AsyncDependency: TypeAlias = Callable[..., Awaitable[Any]] DependencyOverrides: TypeAlias = Dict[Dependency, Dependency] # Route Types RouteHandler: TypeAlias = Callable[..., Any] AsyncRouteHandler: TypeAlias = Callable[..., Awaitable[Any]] RouteDecorator: TypeAlias = Callable[[RouteHandler], RouteHandler] # Middleware Types MiddlewareCallable: TypeAlias = Callable[[Request, Callable[[Request], Awaitable[Response]]], Awaitable[Response]] # Security Types SecurityScheme: TypeAlias = Union[HTTPBearer, OAuth2PasswordBearer] TokenData: TypeAlias = Dict[str, Any] # Enhanced Base Models with proper typing class TypedBaseModel(BaseModel): """Enhanced BaseModel with better typing support.""" class Config: # Enable ORM mode for database models from_attributes = True # Use enum values use_enum_values = True # Validate assignment validate_assignment = True # Allow population by field name allow_population_by_field_name = True # JSON encoders for custom types json_encoders = { datetime: lambda v: v.isoformat(), date: lambda v: v.isoformat(), Decimal: lambda v: str(v), UUID: lambda v: str(v), Path: lambda v: str(v), } @classmethod def get_field_types(cls) -> Dict[str, Any]: """Get field types for the model.""" return get_type_hints(cls) def to_dict(self, exclude_none: bool = True) -> Dict[str, Any]: """Convert model to dictionary.""" return self.dict(exclude_none=exclude_none) @classmethod def from_dict(cls, data: Dict[str, Any]) -> Self: """Create model from dictionary.""" return cls(**data) # Request/Response Models class APIRequest(TypedBaseModel): """Base API request model.""" request_id: Optional[str] = Field(None, description="Request tracking ID") timestamp: Optional[datetime] = Field(default_factory=datetime.utcnow, description="Request timestamp") class APIResponse(TypedBaseModel, Generic[T]): """Generic API response model.""" success: bool = Field(True, description="Request success status") data: Optional[T] = Field(None, description="Response data") message: Optional[str] = Field(None, description="Response message") errors: Optional[List[str]] = Field(None, description="Error messages") timestamp: datetime = Field(default_factory=datetime.utcnow, description="Response timestamp") class PaginatedAPIResponse(APIResponse[List[T]]): """Paginated API response model.""" pagination: PaginationInfo # Error Models class APIError(TypedBaseModel): """API error model.""" error_code: str = Field(..., description="Error code") error_message: str = Field(..., description="Error message") error_details: Optional[Dict[str, Any]] = Field(None, description="Additional error details") field_errors: Optional[Dict[str, List[str]]] = Field(None, description="Field-specific errors") class ValidationErrorResponse(APIResponse[None]): """Validation error response.""" success: bool = Field(False) errors: List[APIError] # Authentication Models class UserClaims(TypedBaseModel): """JWT user claims.""" user_id: UserID = Field(..., description="User identifier") username: str = Field(..., description="Username") email: Optional[str] = Field(None, description="User email") roles: List[str] = Field(default_factory=list, description="User roles") permissions: List[str] = Field(default_factory=list, description="User permissions") exp: int = Field(..., description="Token expiration timestamp") iat: int = Field(..., description="Token issued at timestamp") class AuthenticatedUser(TypedBaseModel): """Authenticated user model.""" id: UserID username: str email: Optional[str] = None roles: List[str] = Field(default_factory=list) permissions: List[str] = Field(default_factory=list) is_active: bool = True is_admin: bool = False # Database Models class DatabaseModel(TypedBaseModel): """Base database model with common fields.""" id: Optional[UUID] = Field(None, description="Primary key") created_at: Optional[datetime] = Field(None, description="Creation timestamp") updated_at: Optional[datetime] = Field(None, description="Last update timestamp") is_deleted: bool = Field(False, description="Soft delete flag") # File Upload Models class FileInfo(TypedBaseModel): """File information model.""" filename: str = Field(..., description="Original filename") content_type: str = Field(..., description="MIME content type") size: int = Field(..., ge=0, description="File size in bytes") checksum: Optional[str] = Field(None, description="File checksum") class UploadedFile(FileInfo): """Uploaded file model.""" file_path: str = Field(..., description="Stored file path") url: Optional[str] = Field(None, description="File access URL") upload_timestamp: datetime = Field(default_factory=datetime.utcnow) # WebSocket Models class WebSocketMessage(TypedBaseModel): """WebSocket message model.""" type: str = Field(..., description="Message type") data: Dict[str, Any] = Field(default_factory=dict, description="Message data") timestamp: datetime = Field(default_factory=datetime.utcnow) user_id: Optional[UserID] = Field(None, description="Sender user ID") class WebSocketConnection(Protocol): """WebSocket connection protocol.""" async def send_text(self, data: str) -> None: ... async def send_json(self, data: Dict[str, Any]) -> None: ... async def receive_text(self) -> str: ... async def receive_json(self) -> Dict[str, Any]: ... async def close(self, code: int = 1000) -> None: ... # Background Task Models class TaskResult(TypedBaseModel, Generic[T]): """Background task result model.""" task_id: str = Field(..., description="Task identifier") status: Literal["pending", "running", "completed", "failed"] = Field(..., description="Task status") result: Optional[T] = Field(None, description="Task result") error: Optional[str] = Field(None, description="Error message if failed") started_at: datetime = Field(..., description="Task start timestamp") completed_at: Optional[datetime] = Field(None, description="Task completion timestamp") progress: Optional[int] = Field(None, ge=0, le=100, description="Task progress percentage") # Health Check Models class HealthStatus(TypedBaseModel): """Health status model.""" status: Literal["healthy", "unhealthy", "degraded"] = Field(..., description="Overall status") version: str = Field(..., description="Application version") uptime: float = Field(..., ge=0, description="Uptime in seconds") checks: Dict[str, bool] = Field(default_factory=dict, description="Individual health checks") timestamp: datetime = Field(default_factory=datetime.utcnow) # Configuration Models class AppConfig(TypedBaseModel): """Application configuration model.""" debug: bool = Field(False, description="Debug mode") environment: Literal["development", "staging", "production"] = Field("production") database_url: DatabaseURL = Field(..., description="Database connection URL") redis_url: Optional[str] = Field(None, description="Redis connection URL") secret_key: str = Field(..., description="Application secret key") cors_origins: List[str] = Field(default_factory=list, description="CORS allowed origins") rate_limit: Optional[int] = Field(None, ge=1, description="Rate limit per minute") # Type-safe dependency injection def get_current_user() -> Callable[[], Awaitable[AuthenticatedUser]]: """Dependency for getting current authenticated user.""" async def _get_current_user() -> AuthenticatedUser: # Implementation would go here raise NotImplementedError return _get_current_user def get_database() -> Callable[[], Awaitable[DatabaseConnection]]: """Dependency for getting database connection.""" async def _get_database() -> DatabaseConnection: # Implementation would go here raise NotImplementedError return _get_database # Exception classes with proper typing class APIException(HTTPException): """Base API exception with enhanced typing.""" def __init__( self, status_code: HTTPStatus, detail: Union[str, Dict[str, Any]] = None, headers: Optional[HTTPHeaders] = None, ) -> None: super().__init__(status_code=status_code, detail=detail, headers=headers) class ValidationException(APIException): """Validation error exception.""" def __init__( self, errors: ValidationError, detail: str = "Validation failed", ) -> None: super().__init__(status_code=422, detail={"message": detail, "errors": errors}) class AuthenticationException(APIException): """Authentication error exception.""" def __init__(self, detail: str = "Authentication required") -> None: super().__init__(status_code=401, detail=detail) class AuthorizationException(APIException): """Authorization error exception.""" def __init__(self, detail: str = "Insufficient permissions") -> None: super().__init__(status_code=403, detail=detail) `; } generateDjangoTypes() { return `""" Django-specific type definitions Enhanced typing support for Django applications """ from __future__ import annotations from typing import ( Any, Callable, Dict, List, Optional, Type, Union, get_type_hints, ) from django.db import models from django.http import HttpRequest, HttpResponse, JsonResponse from django.contrib.auth.models import AbstractUser from django.core.exceptions import ValidationError from django.forms import Form, ModelForm from django.views import View from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView # Django Model Types DjangoModel: TypeAlias = Type[models.Model] ModelInstance: TypeAlias = models.Model QuerySet: TypeAlias = models.QuerySet[Any] Manager: TypeAlias = models.Manager[Any] # Request/Response Types DjangoRequest: TypeAlias = HttpRequest DjangoResponse: TypeAlias = HttpResponse DjangoJsonResponse: TypeAlias = JsonResponse # View Types ViewCallable: TypeAlias = Callable[[HttpRequest], HttpResponse] ClassBasedView: TypeAlias = Type[View] # Form Types DjangoForm: TypeAlias = Form DjangoModelForm: TypeAlias = ModelForm # Enhanced Base Model with proper typing class TypedModel(models.Model): """Enhanced Django model with better typing support.""" class Meta: abstract = True objects: Manager[Self] @classmethod def get_field_types(cls) -> Dict[str, Any]: """Get field types for the model.""" return get_type_hints(cls) def to_dict(self, exclude: Optional[List[str]] = None) -> Dict[str, Any]: """Convert model instance to dictionary.""" opts = self._meta data = {} exclude = exclude or [] for field in opts.concrete_fields + opts.many_to_many: if field.name in exclude: continue value = getattr(self, field.name) if isinstance(value, models.Model): value = value.pk elif hasattr(value, 'all'): # Many-to-many or reverse foreign key value = [item.pk for item in value.all()] data[field.name] = value return data @classmethod def from_dict(cls, data: Dict[str, Any]) -> Self: """Create model instance from dictionary.""" return cls(**data) def update_from_dict(self, data: Dict[str, Any], save: bool = True) -> None: """Update model instance from dictionary.""" for key, value in data.items(): if hasattr(self, key): setattr(self, key, value) if save: self.save() # Base Models with Mixins class TimestampMixin(models.Model): """Mixin for timestamp fields.""" created_at: datetime = models.DateTimeField(auto_now_add=True) updated_at: datetime = models.DateTimeField(auto_now=True) class Meta: abstract = True class UUIDMixin(models.Model): """Mixin for UUID primary key.""" id: UUID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Meta: abstract = True class SoftDeleteMixin(models.Model): """Mixin for soft delete functionality.""" is_deleted: bool = models.BooleanField(default=False) deleted_at: Optional[datetime] = models.DateTimeField(null=True, blank=True) class Meta: abstract = True def soft_delete(self) -> None: """Soft delete the instance.""" self.is_deleted = True self.deleted_at = timezone.now() self.save() class BaseModel(TypedModel, TimestampMixin, UUIDMixin, SoftDeleteMixin): """Base model with common fields and functionality.""" class Meta: abstract = True # User Models class TypedUser(AbstractUser): """Enhanced user model with typing.""" email: str = models.EmailField(unique=True) first_name: str = models.CharField(max_length=30) last_name: str = models.CharField(max_length=30) is_verified: bool = models.BooleanField(default=False) phone_number: Optional[str] = models.CharField(max_length=20, blank=True, null=True) date_of_birth: Optional[date] = models.DateField(blank=True, null=True) objects: Manager[Self] class Meta: db_table = 'auth_user' def get_full_name(self) -> str: """Get user's full name.""" return f"{self.first_name} {self.last_name}".strip() def get_display_name(self) -> str: """Get user's display name.""" return self.get_full_name() or self.username # Serializer Types (for Django REST Framework) try: from rest_framework import serializers from rest_framework.request import Request as DRFRequest from rest_framework.response import Response as DRFResponse from rest_framework.viewsets import ModelViewSet DRFSerializer: TypeAlias = serializers.Serializer DRFModelSerializer: TypeAlias = serializers.ModelSerializer DRFRequest: TypeAlias = DRFRequest DRFResponse: TypeAlias = DRFResponse DRFViewSet: TypeAlias = ModelViewSet class TypedModelSerializer(serializers.ModelSerializer): """Enhanced model serializer with typing.""" @classmethod def get_field_types(cls) -> Dict[str, Any]: """Get field types for the serializer.""" return get_type_hints(cls) def to_representation(self, instance: models.Model) -> Dict[str, Any]: """Convert model instance to representation.""" return super().to_representation(instance) def to_internal_value(self, data: Dict[str, Any]) -> Dict[str, Any]: """Convert input data to internal value.""" return super().to_internal_value(data) except ImportError: # Django REST Framework not installed pass # Form Types with Enhanced Validation class TypedForm(Form): """Enhanced form with typing support.""" def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) def clean(self) -> Dict[str, Any]: """Clean form data with type checking.""" cleaned_data = super().clean() return cleaned_data def get_errors_dict(self) -> Dict[str, List[str]]: """Get form errors as dictionary.""" return {field: errors for field, errors in self.errors.items()} class TypedModelForm(ModelForm): """Enhanced model form with typing support.""" def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) def save(self, commit: bool = True) -> models.Model: """Save form with proper typing.""" return super().save(commit=commit) # View Types class TypedView(View): """Enhanced view with typing support.""" def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: """Dispatch request with typing.""" return super().dispatch(request, *args, **kwargs) class TypedListView(ListView, Generic[T]): """Enhanced list view with typing.""" model: Type[T] queryset: Optional[QuerySet[T]] = None def get_queryset(self) -> QuerySet[T]: """Get queryset with proper typing.""" return super().get_queryset() def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: """Get context data with typing.""" return super().get_context_data(**kwargs) class TypedDetailView(DetailView, Generic[T]): """Enhanced detail view with typing.""" model: Type[T] def get_object(self, queryset: Optional[QuerySet[T]] = None) -> T: """Get object with proper typing.""" return super().get_object(queryset) # Database Types class TypedQuerySet(QuerySet, Generic[T]): """Enhanced queryset with typing.""" def filter(self, **kwargs: Any) -> TypedQuerySet[T]: """Filter with typing.""" return super().filter(**kwargs) # type: ignore def exclude(self, **kwargs: Any) -> TypedQuerySet[T]: """Exclude with typing.""" return super().exclude(**kwargs) # type: ignore def order_by(self, *field_names: str) -> TypedQuerySet[T]: """Order by with typing.""" return super().order_by(*field_names) # type: ignore def select_related(self, *fields: str) -> TypedQuerySet[T]: """Select related with typing.""" return super().select_related(*fields) # type: ignore def prefetch_related(self, *lookups: str) -> TypedQuerySet[T]: """Prefetch related with typing.""" return super().prefetch_related(*lookups) # type: ignore class TypedManager(Manager, Generic[T]): """Enhanced manager with typing.""" def get_queryset(self) -> TypedQuerySet[T]: """Get queryset with typing.""" return TypedQuerySet(self.model, using=self._db) def filter(self, **kwargs: Any) -> TypedQuerySet[T]: """Filter with typing.""" return self.get_queryset().filter(**kwargs) def exclude(self, **kwargs: Any) -> TypedQuerySet[T]: """Exclude with typing.""" return self.get_queryset().exclude(**kwargs) def create(self, **kwargs: Any) -> T: """Create with typing.""" return super().create(**kwargs) # type: ignore def get_or_create(self, **kwargs: Any) -> Tuple[T, bool]: """Get or create with typing.""" return super().get_or_create(**kwargs) # type: ignore # Settings Types class TypedSettings: """Type-safe Django settings.""" DEBUG: bool SECRET_KEY: str ALLOWED_HOSTS: List[str] DATABASES: Dict[str, Dict[str, Any]] INSTALLED_APPS: List[str] MIDDLEWARE: List[str] ROOT_URLCONF: str TEMPLATES: List[Dict[str, Any]] STATIC_URL: str STATIC_ROOT: Optional[str] MEDIA_URL: str MEDIA_ROOT: str TIME_ZONE: str USE_TZ: bool LANGUAGE_CODE: str USE_I18N: bool USE_L10N: bool # Admin Types try: from django.contrib import admin class TypedModelAdmin(admin.ModelAdmin, Generic[T]): """Enhanced model admin with typing.""" model: Type[T] def get_queryset(self, request: HttpRequest) -> QuerySet[T]: """Get queryset with typing.""" return super().get_queryset(request) def save_model(self, request: HttpRequest, obj: T, form: Form, change: bool) -> None: """Save model with typing.""" super().save_model(request, obj, form, change) except ImportError: pass # Signal Types from django.db.models.signals import post_save, pre_save, post_delete, pre_delete from django.dispatch import receiver SignalSender: TypeAlias = Type[models.Model] SignalReceiver: TypeAlias = Callable[[Type[models.Model], models.Model, bool, Any], None] def typed_receiver( signal: Any, sender: Optional[SignalSender] = None, weak: bool = True, dispatch_uid: Optional[str] = None, ) -> Callable[[SignalReceiver], SignalReceiver]: """Type-safe signal receiver decorator.""" return receiver(signal, sender=sender, weak=weak, dispatch_uid=dispatch_uid) # Cache Types from django.core.cache import cache from django.core.cache.backends.base import BaseCache CacheKey: TypeAlias = str CacheValue: TypeAlias = Any CacheTimeout: TypeAlias = Optional[int] class TypedCache: """Type-safe cache wrapper.""" def __init__(self, cache_backend: BaseCache = cache) -> None: self._cache = cache_backend def get(self, key: CacheKey, default: Optional[T] = None) -> Optional[T]: """Get value from cache with typing.""" return self._cache.get(key, default) def set(self, key: CacheKey, value: T, timeout: CacheTimeout = None) -> None: """Set value in cache with typing.""" self._cache.set(key, value, timeout) def delete(self, key: CacheKey) -> None: """Delete value from cache.""" self._cache.delete(key) def get_or_set(self, key: CacheKey, default: Callable[[], T], timeout: CacheTimeout = None) -> T: """Get or set value in cache with typing.""" return self._cache.get_or_set(key, default, timeout) `; } generateFlaskTypes() { return `""" Flask-specific type definitions Enhanced typing support for Flask applications """ from __future__ import annotations from typing import ( Any, Callable, Dict, List, Optional, Tuple, Union, get_type_hints, ) from flask import Flask, Request, Response, jsonify, g from flask.views import View, MethodView from werkzeug.wrappers import Response as WerkzeugResponse from werkzeug.exceptions import HTTPException # Flask Application Types FlaskApp: TypeAlias = Flask FlaskRequest: TypeAlias = Request FlaskResponse: TypeAlias = Union[Response, WerkzeugResponse, str, Tuple[str, int], Tuple[str, int, Dict[str, str]]] # Route Types RouteHandler: TypeAlias = Callable[..., FlaskResponse] RouteDecorator: TypeAlias = Callable[[RouteHandler], RouteHandler] BlueprintHandler: TypeAlias = Callable[..., FlaskResponse] # View Types FlaskView: TypeAlias = View FlaskMethodView: TypeAlias = MethodView # Enhanced Flask Application class TypedFlask(Flask): """Enhanced Flask application with typing support.""" def __init__(self, import_name: str, **kwargs: Any) -> None: super().__init__(import_name, **kwargs) self._view_functions: Dict[str, RouteHandler] = {} def route( self, rule: str, **options: Any, ) -> RouteDecorator: """Route decorator with typing.""" return super().route(rule, **options) def add_url_rule( self, rule: str, endpoint: Optional[str] = None, view_func: Optional[RouteHandler] = None, **options: Any, ) -> None: """Add URL rule with typing.""" super().add_url_rule(rule, endpoint, view_func, **options) def errorhandler( self, code_or_exception: Union[int, type[Exception]], ) -> Callable[[Callable[[Exception], FlaskResponse]], Callable[[Exception], FlaskResponse]]: """Error handler decorator with typing.""" return super().errorhandler(code_or_exception) # Request Context Types class RequestContext: """Type-safe request context.""" def __init__(self) -> None: self._data: Dict[str, Any] = {} def get(self, key: str, default: Optional[T] = None) -> Optional[T]: """Get value from request context.""" return self._data.get(key, default) def set(self, key: str, value: T) -> None: """Set value in request context.""" self._data[key] = value def pop(self, key: str, default: Optional[T] = None) -> Optional[T]: """Pop value from request context.""" return self._data.pop(key, default) # Enhanced Request Class class TypedRequest(Request): """Enhanced request with typing support.""" @property def json_data(self) -> Optional[Dict[str, Any]]: """Get JSON data with typing.""" if self.is_json: return self.get_json() return None def get_param(self, key: str, default: Optional[T] = None, param_type: Type[T] = str) -> Optional[T]: """Get request parameter with type conversion.""" value = self.args.get(key, default) if value is not None and param_type != str: try: return param_type(value) except (ValueError, TypeError): return default return value def get_form_data(self, key: str, default: Optional[T] = None) -> Optional[T]: """Get form data with typing.""" return self.form.get(key, default) # Response Types class APIResponse: """Type-safe API response builder.""" @staticmethod def success( data: Optional[T] = None, message: Optional[str] = None, status_code: int = 200, ) -> FlaskResponse: """Create success response.""" response_data = { "success": True, "data": data, "message": message, } return jsonify(response_data), status_code @staticmethod def error( message: str, errors: Optional[Dict[str, List[str]]] = None, status_code: int = 400, ) -> FlaskResponse: """Create error response.""" response_data = { "success": False, "message": message, "errors": errors, } return jsonify(response_data), status_code @staticmethod def paginated( data: List[T], pagination: PaginationInfo, message: Optional[str] = None, ) -> FlaskResponse: """Create paginated response.""" response_data = { "success": True, "data": data, "pagination": pagination, "message": message, } return jsonify(response_data) # Blueprint Types from flask import Blueprint class TypedBlueprint(Blueprint): """Enhanced blueprint with typing support.""" def __init__(self, name: str, import_name: str, **kwargs: Any) -> None: super().__init__(name, import_name, **kwargs) def route( self, rule: str, **options: Any, ) -> RouteDecorator: """Route decorator with typing.""" return super().route(rule, **options) def before_request( self, func: Callable[[], Optional[FlaskResponse]], ) -> Callable[[], Optional[FlaskResponse]]: """Before request decorator with typing.""" return super().before_request(func) def after_request( self, func: Callable[[FlaskResponse], FlaskResponse], ) -> Callable[[FlaskResponse], FlaskResponse]: """After request decorator with typing.""" return super().after_request(func) # Database Integration Types (SQLAlchemy) try: from flask_sqlalchemy import SQLAlchemy from sqlalchemy.orm import DeclarativeBase class TypedSQLAlchemy(SQLAlchemy): """Enhanced SQLAlchemy with typing.""" Model: Type[DeclarativeBase] def __init__(self, app: Optional[Flask] = None, **kwargs: Any) -> None: super().__init__(app, **kwargs) class BaseModel(DeclarativeBase): """Base model with common functionality.""" @classmethod def get_field_types(cls) -> Dict[str, Any]: """Get field types for the model.""" return get_type_hints(cls) def to_dict(self, exclude: Optional[List[str]] = None) -> Dict[str, Any]: """Convert model to dictionary.""" exclude = exclude or [] return { column.name: getattr(self, column.name) for column in self.__table__.columns if column.name not in exclude } @classmethod def from_dict(cls, data: Dict[str, Any]) -> Self: """Create model from dictionary.""" return cls(**data) def update_from_dict(self, data: Dict[str, Any]) -> None: """Update model from dictionary.""" for key, value in data.items(): if hasattr(self, key): setattr(self, key, value) except ImportError: # Flask-SQLAlchemy not installed pass # Form Types (WTForms) try: from flask_wtf import FlaskForm from wtforms import Field class TypedFlaskForm(FlaskForm): """Enhanced Flask form with typing.""" def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) def validate(self, extra_validators: Optional[Dict[str, List[Callable]]] = None) -> bool: """Validate form with typing.""" return super().validate(extra_validators) def get_errors_dict(self) -> Dict[str, List[str]]: """Get form errors as dictionary.""" return {field.name: field.errors for field in self if field.errors} except ImportError: # Flask-WTF not installed pass # Authentication Types class User: """Base user model.""" def __init__( self, id: UserID, username: str, email: Optional[str] = None, is_active: bool = True, roles: Optional[List[str]] = None, ) -> None: self.id = id self.username = username self.email = email self.is_active = is_active self.roles = roles or [] def is_authenticated(self) -> bool: """Check if user is authenticated.""" return True def is_anonymous(self) -> bool: """Check if user is anonymous.""" return False def get_id(self) -> str: """Get user ID as string.""" return str(self.id) def has_role(self, role: str) -> bool: """Check if user has specific role.""" return role in self.roles # Session Types class SessionManager: """Type-safe session manager.""" @staticmethod def get(key: str, default: Optional[T] = None) -> Optional[T]: """Get value from session.""" from flask import session return session.get(key, default) @staticmethod def set(key: str, value: T) -> None: """Set value in session.""" from flask import session session[key] = value @staticmethod def pop(key: str, default: Optional[T] = None) -> Optional[T]: """Pop value from session.""" from flask import session return session.pop(key, default) @staticmethod def clear() -> None: """Clear session.""" from flask import session session.clear() # Middleware Types MiddlewareCallable: TypeAlias = Callable[[FlaskRequest], Optional[FlaskResponse]] class TypedMiddleware: """Base middleware class with typing.""" def __init__(self, app: Flask) -> None: self.app = app self.wsgi_app = app.wsgi_app app.wsgi_app = self def __call__(self, environ: Dict[str, Any], start_response: Callable) -> Any: """WSGI application call.""" return self.wsgi_app(environ, start_response) # Configuration Types class FlaskConfig: """Type-safe Flask configuration.""" DEBUG: bool = False TESTING: bool = False SECRET_KEY: Optional[str] = None DATABASE_URI: Optional[str] = None SQLALCHEMY_DATABASE_URI: Optional[str] = None SQLALCHEMY_TRACK_MODIFICATIONS: bool = False WTF_CSRF_ENABLED: bool = True WTF_CSRF_SECRET_KEY: Optional[str] = None SESSION_COOKIE_SECURE: bool = True SESSION_COOKIE_HTTPONLY: bool = True SESSION_COOKIE_SAMESITE: str = "Lax" # Error Handler Types ErrorHandler: TypeAlias = Callable[[Exception], FlaskResponse] class TypedErrorHandler: """Type-safe error handlers.""" @staticmethod def handle_404(error: Exception) -> FlaskResponse: """Handle 404 errors.""" return APIResponse.error("Resource not found", status_code=404) @staticmethod def handle_500(error: Exception) -> FlaskResponse: """Handle 500 errors.""" return APIResponse.error("Internal server error", status_code=500) @staticmethod def handle_validation_error(error: Exception) -> FlaskResponse: """Handle validation errors.""" return APIResponse.error("Validation failed", status_code=422) # Decorator Types def typed_route( rule: str, methods: Optional[List[HTTPMethod]] = None, **options: Any, ) -> RouteDecorator: """Type-safe route decorator.""" def decorator(func: RouteHandler) -> RouteHandler: func.__route_rule__ = rule func.__route_methods__ = methods or ['GET'] func.__route_options__ = options return func return decorator def requires_auth(func: RouteHandler) -> RouteHandler: """Authentication required decorator.""" def wrapper(*args: Any, **kwargs: Any) -> FlaskResponse: # Implementation would check authentication return func(*args, **kwargs) return wrapper def requires_role(role: str) -> RouteDecorator: """Role required decorator.""" def decorator(func: RouteHandler) -> RouteHandler: def wrapper(*args: Any, **kwargs: Any) -> FlaskResponse: # Implementation would check user role return func(*args, **kwargs) return wrapper return decorator # Cache Types (Flask-Caching) try: from flask_caching import Cache class TypedCache(Cache): """Enhanced cache with typing.""" def get(self, key: str) -> Optional[T]: """Get value from cache with typing.""" return super().get(key) def set(self, key: str, value: T, timeout: Optional[int] = None) -> bool: """Set value in cache with typing.""" return super().set(key, value, timeout) def delete(self, key: str) -> bool: """Delete value from cache.""" return super().delete(key) def cached( self, timeout: Optional[int] = None, key_prefix: str = 'view/%s', unless: Optional[Callable[[], bool]] = None, ) -> RouteDecorator: """Cached decorator with typing.""" return super().cached(timeout, key_prefix, unless) except ImportError: # Flask-Caching not installed pass `; } generateTornadoTypes() { return `""" Tornado-specific type definitions Enhanced typing support for Tornado applications """ from __future__ import annotations from typing import ( Any, Awaitable, Callable, Dict, List, Optional, Union, get_type_hints, ) import tornado.web import tornado.websocket from tornado.concurrent import Future from tornado.httpclient import HTTPRequest, HTTPResponse from tornado.ioloop import IOLoop from tornado.options import define, options # Tornado Application Types TornadoApp: TypeAlias = tornado.web.Application TornadoRequest: TypeAlias = tornado.httputil.HTTPServerRequest TornadoResponse: TypeAlias = None # Tornado doesn't return responses directly # Handler Types RequestHandler: TypeAlias = tornado.web.RequestHandler WebSocketHandler: TypeAlias = tornado.websocket.WebSocketHandler StaticFileHandler: TypeAlias = tornado.web.StaticFileHandler # Async Types TornadoFuture: TypeAlias = Future[Any] AsyncHandler: TypeAlias = Callable[..., Awaitable[None]] # Enhanced Request Handler class TypedRequestHandler(tornado.web.RequestHandler): """Enhanced request handler with typing support.""" def initialize(self, **kwargs: Any) -> None: """Initialize handler with typed arguments.""" super().initialize(**kwargs) def prepare(self) -> Optional[Awaitable[None]]: """Prepare request with typing.""" return super().prepare() def get_argument( self, name: str, default: Union[None, str, tornado.web._ArgDefaultMarker] = tornado.web._ARG_DEFAULT, strip: bool = True, ) -> str: """Get argument with typing.""" return super().get_argument(name, default, strip) def get_arguments(self, name: str, strip: bool = True) -> List[str]: """Get arguments with typing.""" return super().get_arguments(name, strip) def get_body_argument( self, name: str, default: Union[None, str, tornado.web._ArgDefaultMarker] = tornado.web._ARG_DEFAULT, strip: bool = True, ) -> str: """Get body argument with typing.""" return super().get_body_argument(name, default, strip) def get_body_arguments(self, name: str, strip: bool = True) -> List[str]: """Get body arguments with typing.""" return super().get_body_arguments(name, strip) def get_json_argument(self, name: str, default: Optional[T] = None) -> Optional[T]: """Get JSON argument with typing.""" try: json_data = self.get_json_body() return json_data.get(name, default) if json_data else default except (ValueError, TypeError): return default def get_json_body(self) -> Optional[Dict[str, Any]]: """Get JSON body with typing.""" try: import json return json.loads(self.request.body.decode('utf-8')) except (ValueError, UnicodeDecodeError): return None def write_json(self, obj: Any) -> None: """Write JSON response with typing.""" import json self.set_header("Content-Type", "application/json") self.write(json.dumps(obj, default=str)) def write_error(self, status_code: int, **kwargs: Any) -> None: """Write error response with typing.""" self.set_status(status_code) error_data = { "error": True, "status_code": status_code, "message": kwargs.get("message", "An error occurred"), } self.write_json(error_data) # WebSocket Handler with Typing class TypedWebSocketHandler(tornado.websocket.WebSocketHandler): """Enhanced WebSocket handler with typing support.""" def open(self, *args: Any, **kwargs: Any) -> Optional[Awaitable[None]]: """Open WebSocket connection with typing.""" return super().open(*args, **kwargs) def on_message(self, message: Union[str, bytes]) -> Optional[Awaitable[None]]: """Handle WebSocket message with typing.""" return super().on_message(message) def on_close(self) -> None: """Handle WebSocket close with typing.""" super().on_close() def write_message( self, message: Union[str, bytes, Dict[str, Any]], binary: bool = False, ) -> Future[None]: """Write WebSocket message with typing.""" if isinstance(message, dict): import json message = json.dumps(message) return super().write_message(message, binary) def send_json(self, data: Dict[str, Any]) -> Future[None]: """Send JSON data via WebSocket.""" import json return self.write_message(json.dumps(data)) def send_error(self, error: str, code: Optional[int] = None) -> Future[None]: """Send error message via WebSocket.""" error_data = { "type": "error", "error": error, "code": code, } return self.send_json(error_data) # Application with Enhanced Typing class TypedApplication(tornado.web.Application): """Enhanced Tornado application with typing support.""" def __init__( self, handlers: Optional[List[Union[tornado.web.URLSpec, Tuple[str, Any], Tuple[str, Any, Dict[str, Any]]]]] = None, default_host: Optional[str] = None, transforms: Optional[List[Type[tornado.web.OutputTransform]]] = None, **settings: Any, ) -> None: super().__init__(handlers, default_host, transforms, **settings) def add_handlers( self, host_pattern: str, host_handlers: List[Union[tornado.web.URLSpec, Tuple[str, Any], Tuple[str, Any, Dict[str, Any]]]], ) -> None: """Add handlers with typing.""" super().add_handlers(host_pattern, host_handlers) # URL Routing Types URLPattern: TypeAlias = Union[ tornado.web.URLSpec, Tuple[str, Type[tornado.web.RequestHandler]], Tuple[str, Type[tornado.web.RequestHandler], Dict[str, Any]], ] def typed_url( pattern: str, handler: Type[tornado.web.RequestHandler], kwargs: Optional[Dict[str, Any]] = None, name: Optional[str] = None, ) -> tornado.web.URLSpec: """Create typed URL specification.""" return tornado.web.URLSpec(pattern, handler, kwargs, name) # Database Integration Types try: import motor.motor_tornado class TypedMotorClient: """Enhanced Motor client with typing.""" def __init__(self, uri: str, **kwargs: Any) -> None: self.client = motor.motor_tornado.MotorClient(uri, **kwargs) def get_database(self, name: str) -> motor.motor_tornado.MotorDatabase: """Get database with typing.""" return self.client[name] def close(self) -> None: """Close client connection.""" self.client.close() except ImportError: # Motor not installed pass # Authentication and Authorization class AuthMixin: """Authentication mixin for request handlers.""" def get_current_user(self) -> Optional[Dict[str, Any]]: """