本文目录导读:

在 Django 中配置健康检查端点(Health Check Endpoint)通常用于监控应用是否正常运行,比如在 Kubernetes 的存活探针(liveness probe)和就绪探针(readiness probe)中使用,以下是几种常见的配置方法:
使用 django-health-check 库(推荐)
这是最流行且功能完整的方案。
安装
pip install django-health-check
配置 settings.py
INSTALLED_APPS = [
# ...
'health_check', # 基础健康检查
'health_check.db', # 数据库检查
'health_check.cache', # 缓存检查
'health_check.storage', # 文件存储检查
'health_check.contrib.migrations', # 数据库迁移检查
'health_check.contrib.celery', # Celery 检查(可选)
'health_check.contrib.redis', # Redis 检查(可选)
]
配置 URL
# urls.py
from django.urls import path, include
urlpatterns = [
# ...
path('ht/', include('health_check.urls')),
]
访问端点
# 基础检查 GET /ht/ # 仅检查特定组件 GET /ht/?check=db&check=cache # 返回 JSON 格式 GET /ht/?format=json
Kubernetes 探针配置示例
livenessProbe:
httpGet:
path: /ht/
port: 8000
httpHeaders:
- name: Accept
value: application/json
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ht/
port: 8000
httpHeaders:
- name: Accept
value: application/json
initialDelaySeconds: 5
periodSeconds: 5
自定义简单健康检查
如果只需要最基本的检查,可以自己实现:
创建视图
# views.py
from django.http import JsonResponse
from django.db import connections
from django.db.utils import OperationalError
def health_check(request):
status = 200
response_data = {
'status': 'healthy',
'database': 'ok'
}
# 检查数据库连接
db_conn = connections['default']
try:
db_conn.ensure_connection()
except OperationalError:
response_data['database'] = 'error'
status = 500
response_data['status'] = 'unhealthy'
# 可以添加更多检查...
# 检查缓存
# 检查磁盘空间等
return JsonResponse(response_data, status=status)
配置 URL
# urls.py
from django.urls import path
from . import views
urlpatterns = [
# ...
path('health/', views.health_check, name='health_check'),
]
使用 Django REST Framework
如果项目已经使用了 DRF:
创建 API 视图
# views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.db import connection
@api_view(['GET'])
def health_check(request):
try:
# 测试数据库连接
with connection.cursor() as cursor:
cursor.execute("SELECT 1")
return Response({
'status': 'healthy',
'database': 'connected'
}, status=status.HTTP_200_OK)
except Exception as e:
return Response({
'status': 'unhealthy',
'error': str(e)
}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
配置 URL
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('api/health/', views.health_check, name='health_check'),
]
推荐配置
对于生产环境,建议:
-
使用 django-health-check,因为它提供了:
- 多种组件检查(数据库、缓存、存储等)
- JSON 格式输出
- 详细的错误信息
- 与 Kubernetes 良好集成
-
分别配置存活探针和就绪探针:
- 存活探针(Liveness):只检查应用是否活着
- 就绪探针(Readiness):检查所有依赖是否就绪(数据库、缓存等)
-
添加认证(如果需要):
# 使用装饰器或中间件保护健康检查端点 from django.contrib.admin.views.decorators import staff_member_required from django.utils.decorators import method_decorator
@method_decorator(staff_member_required, name='dispatch') class HealthCheckView(...): pass
这样配置后,你就可以通过 `/ht/` 或自定义的端点来监控 Django 应用的健康状态了。