Cost Savings
Hire dedicated Python developers who can integrate LLMs, build reliable RAG pipelines, and ship secure APIs without handholding. If you're building AI-enabled features or data workflows, our remote Python developers are ready.
A developer who's been with you for years knows your data models, your API contracts, and your edge cases. Our Python developers stay long enough to become experts on your systems. 72% of our clients have stayed 5+ years.
Risk-Free Trial
One week on real projects.
No payment unless you continue.
Truly Dedicated
One developer,
full-time, works only for you.
Month-to-Month
No lock-in. Cancel anytime.
Most stay for years.
Some of our developers have worked with the same client for over a decade
72% of clients have stayed 5+ years
22 years in business - clients retained for up to 19 years
We test developers on internal projects before trusting them with yours
Developers complete secure coding training before client deployment
Some of our developers have worked with the same client for over a decade
72% of clients have stayed 5+ years
22 years in business - clients retained for up to 19 years
We test developers on internal projects before trusting them with yours
Developers complete secure coding training before client deployment
Some of our developers have worked with the same client for over a decade
72% of clients have stayed 5+ years
22 years in business - clients retained for up to 19 years
We test developers on internal projects before trusting them with yours
Developers complete secure coding training before client deployment
Python for AI Apps
RAG & Agentic AI
Get more value with AI-Driven Productivity
# Python 3.11+ - FastAPI WebSocket with Security & Best Practices
from typing import Annotated
from datetime import datetime, timezone
from contextlib import asynccontextmanager
from urllib.parse import quote
import secrets
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Depends, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
from pydantic import ValidationError
import nh3
from app.core.logging import get_logger
from app.core.config import settings
from app.core.metrics import metrics
from app.core.redis import get_redis_client
from app.schemas.websocket import MessageSchema, WebSocketEventSchema
from app.services.auth import AuthService
from app.services.rate_limiter import RateLimiter
from app.managers.connection_manager import ConnectionManager
logger = get_logger(__name__)
# Initialize services with dependency injection
auth_service = AuthService()
rate_limiter = RateLimiter(redis_client=get_redis_client())
connection_manager = ConnectionManager(
redis_client=get_redis_client(),
logger=logger
)
# Security headers middleware
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next) -> Response:
response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
response.headers["Content-Security-Policy"] = "default-src 'self'"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
return response
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Manage application lifecycle with proper cleanup"""
await connection_manager.initialize()
logger.info("Application started", version=settings.APP_VERSION)
yield
await connection_manager.cleanup()
logger.info("Application shutdown complete")
# Create FastAPI app
app = FastAPI(
title=settings.APP_NAME,
version=settings.APP_VERSION,
lifespan=lifespan,
docs_url="/docs" if settings.DEBUG else None,
redoc_url=None, # Disable redoc in production
openapi_url="/openapi.json" if settings.DEBUG else None
)
# Add security middleware stack
app.add_middleware(SecurityHeadersMiddleware)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=settings.ALLOWED_HOSTS)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS, # Explicit origins, not "*"
allow_credentials=True,
allow_methods=["GET", "POST"], # Restrict methods
allow_headers=["Authorization", "Content-Type"],
max_age=600,
)
def sanitize_input(text: str, max_length: int = 1000) -> str:
"""Sanitize user input to prevent XSS"""
# Strip all HTML tags and limit length
cleaned = nh3.clean(text, tags=set())
return cleaned[:max_length].strip()
def validate_room_id(room_id: str) -> str:
"""Validate and sanitize room ID"""
if not room_id or len(room_id) > 64:
raise ValueError("Invalid room ID")
# Only allow alphanumeric and hyphens
if not room_id.replace("-", "").isalnum():
raise ValueError("Room ID contains invalid characters")
return quote(room_id, safe="")
@app.websocket("/ws/{room_id}")
async def websocket_endpoint(
websocket: WebSocket,
room_id: str,
user: Annotated[str, Depends(auth_service.get_user_from_token)],
_rate_limit: Annotated[None, Depends(rate_limiter.check)]
):
"""WebSocket endpoint with auth, rate limiting, and input validation"""
# Validate room ID
try:
safe_room_id = validate_room_id(room_id)
except ValueError as e:
await websocket.close(code=status.WS_1008_POLICY_VIOLATION, reason=str(e))
return
# Check room access
if not await auth_service.can_access_room(user, safe_room_id):
await websocket.close(code=status.WS_1008_POLICY_VIOLATION, reason="Access denied")
return
# Accept the WebSocket connection
await websocket.accept()
# Generate secure client ID
client_id = secrets.token_urlsafe(16)
# Connect client
await connection_manager.connect(
websocket=websocket,
room_id=safe_room_id,
user_id=user,
client_id=client_id
)
try:
while True:
raw_data = await websocket.receive_text()
# Validate message size
if len(raw_data) > 10_000:
await connection_manager.send_error(client_id, "MESSAGE_TOO_LARGE")
continue
try:
event = WebSocketEventSchema.model_validate_json(raw_data)
except ValidationError as e:
logger.warning("Invalid message", errors=e.errors(), client=client_id)
await connection_manager.send_error(client_id, "INVALID_FORMAT")
continue
match event.type:
case "message":
# Sanitize message content
safe_text = sanitize_input(event.payload.get("text", ""))
if not safe_text:
continue
message_id = await connection_manager.process_message(
room_id=safe_room_id,
user_id=user,
text=safe_text
)
metrics.record_message_sent(safe_room_id, user)
logger.debug("Message sent", message_id=message_id)
case "typing":
await connection_manager.broadcast_typing(
room_id=safe_room_id,
user_id=user,
is_typing=bool(event.payload.get("is_typing"))
)
case "heartbeat":
await connection_manager.heartbeat(client_id)
case _:
logger.warning("Unknown event", type=event.type)
except WebSocketDisconnect:
logger.info("Client disconnected", client=client_id, room=safe_room_id)
except Exception as e:
logger.error("WebSocket error", error=str(e), client=client_id, exc_info=True)
metrics.record_error("websocket_error")
finally:
await connection_manager.disconnect(client_id)
@app.get("/health")
async def health_check():
"""Health check with service status"""
redis_ok = await connection_manager.check_redis_health()
return {
"status": "healthy" if redis_ok else "degraded",
"timestamp": datetime.now(timezone.utc).isoformat(),
"version": settings.APP_VERSION
}Developers Who Stay
When you hire dedicated Python developers from us, they stay for years, not months. They accumulate deep knowledge of your systems & business, and become increasingly productive.
Pre-Tested Expertise
We won't assign a developer to you before testing them on our own projects. CTO-level evaluation ensures every developer meets our high standards.
Secure Code
All developers complete secure coding training. They write defensible code to protect your app, your users, your data and your reputation.
$100 AI Credits Included
$100/month in AI credits included. Your developer can use AI tools (with your consent) for accelerated delivery and testing of AI features.
Senior Manager Service
Every inquiry - before and after you hire - is handled personally by senior managers. Enterprise professionalism, boutique attention.
No More Headaches
No more time lost to repeated recruitment rounds and high turnover. No more substandard platform support. Experience genuine partnership.
Build New Python Systems
Ship new Python systems with confidence
Rescue Existing Python Code
Turn messy code into maintainable systems
Platforms match you with freelancers. We employ developers who build careers with us - and long-term relationships with you.
Cost Savings
Pre-Deployment Testing
Track Record
Client Retention
Staff Longevity
Secure Coding Training
" I have to say that in my entire life I have never ever come across the dedication to detail and the willingness to work at high pressure levels to deadlines as I have experienced with your employees. Your company has my respect, I never thought things would work out as well as they have. Congratulations to you all for such a wonderful service. "
Graeme
" I am amazed with Bidhun. He is very responsive to tasks that I give him. His communication is excellent - way above my expectations and the quality of his work is superior to anyone I have worked with before. He is to be commended on his attendance and commitment to my projects. "
AK
" I just wanted to let you know that I am very pleased with your service. The programmer assigned to me is doing a fine job. He seems to work consistently, he communicates clearly, and he offers good insights concerning our projects. I appreciate his short accurate daily project reports. "
Paul
" Under no circumstances can I lose my developer. I'd rather lose my right arm than him. "
CF
" Thank you so much for all your detailed responses. I have never dealt with a programming company that is so professional. "
Brian
" I find your company and service to be VERY professional and I get more and more excited about our future work! "
Eric
Get In Touch
Reach out - a senior manager will personally discuss your Python project needs.
Get Matched
We pair you with a developer we've already vetted and tested on internal projects.
Try Risk-Free
One week of real work on your projects. No payment unless you want to continue.
Build Together
Month-to-month from there. Your developer learns your codebase, your data models, and stays.
Skilled Python Developer
Solid foundation
One-week obligation-free trial
No credit card required
Seasoned Python Developer
Most popular
One-week obligation-free trial
No credit card required
Lead Python Developer
Complex projects
One-week obligation-free trial
No credit card required
Tell us what skills you are looking for and we will send you a discount code.
Get no-fuss access to seasoned staff by the week. No minimum commitment. Just extra capacity when you need it.
Software Testers
Full-stack QA: manual, automation, performance, security, mobile.
US$499/week
Web Designers
UI/UX, Figma, responsive design, brand consistency.
US$499/week
Server Administrators
Linux, Docker, security, installations, upgrades, etc.
US$499/week
All from the same trusted partner. 22 years in business. Staff who stay.
Enterprise professionalism. Boutique attention.
Contact Us