gRPC Integration
Build high-performance gRPC APIs with full Django integration - ORM, authentication, admin interface, and automatic service discovery.
๐ฏ What is This?โ
Django-CFG provides a complete gRPC server that integrates seamlessly with Django:
- โ Async Support - High-concurrency async server with streaming (1000+ concurrent requests)
- โ Auto-Discovery - Services automatically registered from Django apps
- โ Django Integration - Full ORM, auth, admin, signals access
- โ API Key Authentication - Simple, secure API key management with admin interface
- โ Request Logging - All requests logged to database with API key tracking
- โ Server Monitoring - Real-time server status and uptime tracking
- โ REST API - Monitor services and manage API keys via REST endpoints
- โ Production-Ready - Interceptors, error handling, monitoring
- โ Developer-Friendly - Base classes, helpers, zero configuration
๐ Quick Startโ
1. Installโ
pip install django-cfg[grpc]
2. Enable in Configโ
# api/config.py
from django_cfg import DjangoConfig, GRPCConfig, GRPCServerConfig
class MyConfig(DjangoConfig):
grpc = GRPCConfig(
enabled=True,
server=GRPCServerConfig(
host="[::]",
port=50051,
),
enabled_apps=["apps.users", "apps.products"],
)
3. Create Serviceโ
# apps/users/grpc_services.py
from django_cfg.apps.integrations.grpc.services import BaseService
from django.contrib.auth import get_user_model
User = get_user_model()
class UserService(BaseService):
def GetUser(self, request, context):
user = User.objects.get(id=request.user_id)
return UserResponse(
id=user.id,
username=user.username,
email=user.email,
)
4. Start Serverโ
python manage.py rungrpc
Output:
๐ Starting gRPC server...
๐ก Server running at [::]:50051
โ
Registered 1 service: api.users.UserService
5. Testโ
grpcurl -plaintext -d '{"user_id": 1}' \
localhost:50051 api.users.UserService/GetUser
That's it! Your gRPC service is running. ๐
๐๏ธ Architectureโ
๐ฏ Key Featuresโ
Auto-Discoveryโ
Services are automatically discovered from your Django apps:
# No registration needed! Just create the file:
# apps/users/grpc_services.py
class UserService(BaseService):
def GetUser(self, request, context):
# Automatically discovered and registered
pass
Discovery locations:
app/grpc_services.pyโapp/grpc_handlers.pyโapp/services/grpc.pyโ
Django Integrationโ
Full access to Django features:
class OrderService(BaseService):
def CreateOrder(self, request, context):
# Django ORM
user = self.require_user(context) # From API key
order = Order.objects.create(user=user)
# Django signals
order_created.send(sender=Order, instance=order)
# Django cache
cache.set(f'order:{order.id}', order, 300)
return OrderResponse(...)
API Key Authenticationโ
Manage API keys through Django Admin for secure service authentication:
Create key:
- Go to Django Admin โ gRPC API Keys
- Click "Add gRPC API Key"
- Fill in name, user, type, expiration
- Save and copy the generated key
Use key:
grpcurl -H "x-api-key: <your-key>" \
localhost:50051 api.users.UserService/GetUser
Features:
- Auto-generated secure keys (64-character hex)
- Managed through Django Admin
- Optional expiration dates
- Usage tracked automatically (request count, last used)
- Easy revocation
- Django SECRET_KEY support for dev/internal use
Example service with auth:
class UserService(BaseService):
def UpdateProfile(self, request, context):
# Require authentication
user = self.require_user(context)
# Check permissions
if not user.has_perm('users.change_profile'):
self.abort_permission_denied(context, "No access")
# Access API key info
api_key = getattr(context, 'api_key', None)
if api_key:
print(f"Request from: {api_key.name}")
# Update profile
user.bio = request.bio
user.save()
return UserResponse(...)
Request Loggingโ
All requests automatically logged to database with API key tracking:
# View in Django Admin
/admin/integrations/grpc/grpcrequestlog/
# Query programmatically
from django_cfg.apps.integrations.grpc.models import GRPCRequestLog
stats = GRPCRequestLog.objects.get_statistics(hours=24)
# {
# "total": 1543,
# "successful": 1489,
# "success_rate": 96.5,
# "avg_duration_ms": 125.3
# }
# Filter by API key
api_key_logs = GRPCRequestLog.objects.filter(
api_key__name="Analytics Service"
)
# Filter by user
user_logs = GRPCRequestLog.objects.filter(
user__username="service_user",
is_authenticated=True
)
# Get recent requests with API key info (via REST API)
# GET /api/grpc/monitor/requests/
# Returns: user_id, username, api_key_id, api_key_name for each request
Server Monitoringโ
Real-time server status tracking:
View in Django Admin: /admin/ โ gRPC Server Status
See server monitoring:
- Server address and port
- Status (running/stopped)
- Uptime
- Registered services
Integration Testingโ
Test your complete gRPC setup with a single command:
python manage.py test_grpc_integration [--app APP_NAME] [--quiet]
What it tests:
- โ Proto file generation
- โ Server startup
- โ API key authentication
- โ Request logging with API key tracking
- โ Service discovery
- โ Automatic cleanup
Example output:
๐งช gRPC Integration Test
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
Step 1/6: Generated proto files
โ
Step 2/6: Started gRPC server (PID: 12345)
โ
Step 3/6: Created test API key
โ
Step 4/6: Client tests passed (3/3)
โ With API key
โ With SECRET_KEY
โ Invalid key (expected failure)
โ
Step 5/6: Request logs verified
โข Total logs: 95
โข With API key: 33
โข With SECRET_KEY: 62
โ
Step 6/6: Cleanup completed
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ All tests passed! (6/6)
Use this command in CI/CD pipelines to verify your gRPC setup before deployment.
๐ Process Flowsโ
Simple Request Flowโ
API Key Authentication Flowโ
Interceptor Chainโ
Base Service Classesโ
Three base classes for common patterns:
# Flexible authentication
from django_cfg.apps.integrations.grpc.services import BaseService
class MyService(BaseService):
pass
# Read-only operations
from django_cfg.apps.integrations.grpc.services import ReadOnlyService
class CatalogService(ReadOnlyService):
pass
# All methods require auth
from django_cfg.apps.integrations.grpc.services import AuthRequiredService
class AccountService(AuthRequiredService):
pass
Dynamic Invocation (Phase 4)โ
Test services without proto files using reflection:
from django_cfg.apps.integrations.grpc.services.grpc_client import DynamicGRPCClient
client = DynamicGRPCClient("localhost", 50051)
# Discover services
services = client.list_services()
# Invoke method
response = client.invoke_method(
"api.users.UserService",
"GetUser",
{"user_id": 1}
)
๐ Request Flowโ
๐ Server Lifecycleโ
Server Statesโ
Development Workflowโ
๐ Documentationโ
Core Guidesโ
- Getting Started - Build your first service (10 min)
- Concepts - Architecture and design patterns
- Configuration - Complete configuration reference
- Authentication - API key authentication
Advanced Topicsโ
- Async Support - High-concurrency async server and streaming
- REST API - REST endpoints for monitoring and management
- Dynamic Invocation - Test without proto files
- FAQ - Common questions and troubleshooting
๐ก Why Django-CFG gRPC?โ
vs. Plain gRPCโ
| Feature | Plain gRPC | Django-CFG gRPC |
|---|---|---|
| Service Registration | Manual | โ Automatic |
| Django ORM | Manual setup | โ Built-in |
| API Key Auth | DIY | โ Built-in with admin |
| Request Logging | DIY | โ Automatic with API key tracking |
| Server Monitoring | DIY | โ Real-time status tracking |
| REST API | None | โ Full monitoring and management API |
| Admin Interface | None | โ Django Admin integration |
| Error Handling | Manual | โ Automatic |
vs. RESTโ
| Aspect | REST | gRPC |
|---|---|---|
| Performance | Good | โ Excellent |
| Binary Protocol | No | โ Yes (smaller, faster) |
| Streaming | Limited | โ Bidirectional |
| Type Safety | Optional | โ Built-in (protobuf) |
| Browser Support | โ Native | Limited (grpc-web) |
| Public APIs | โ Better | Good |
Use gRPC for:
- Microservices communication
- Mobile app backends
- Real-time systems
- High-performance APIs
Use REST for:
- Public APIs
- Browser-based apps
- Simple CRUD
Ready to start? Check out the Getting Started Guide and build your first gRPC service in 10 minutes! ๐