某些需求下,需要通过Django代理后端,比如开发celery定时任务时候,需要代理后端的flower,代理后端可以直接使用Django自带的授权,方便权限控制
具体操作如下
1.安装 django-proxy 包,进行代理
pip install django-proxy
2.编写view,用与代理后端flower
settings.py中添加下面配置
CELERY_FLOWER_PORT = 5566
CELERY_FLOWER_HOST = '127.0.0.1'
CELERY_FLOWER_AUTH = 'flower:flower123.'
flower.py文件如下
import base64
import logging
from django.conf import settings
from django.http import HttpResponse
from django.utils.translation import gettext as _
from django.views.decorators.clickjacking import xframe_options_exempt
from proxy.views import proxy_view
from rest_framework.views import APIView
logger = logging.getLogger(__name__)
flower_url = f'{settings.CELERY_FLOWER_HOST}:{settings.CELERY_FLOWER_PORT}'
class CeleryFlowerView(APIView):
@xframe_options_exempt
def get(self, request, path):
remote_url = 'http://{}/api/flower/{}'.format(flower_url, path)
try:
basic_auth = base64.b64encode(settings.CELERY_FLOWER_AUTH.encode('utf-8')).decode('utf-8')
response = proxy_view(request, remote_url, {
'headers': {
'Authorization': f"Basic {basic_auth}"
}
})
except Exception as e:
logger.warning(f"celery flower service unavailable. {e}")
msg = _("<h3>服务不在线,请联系管理员</h3>")
response = HttpResponse(msg)
return response
@xframe_options_exempt
def post(self, request, path):
return self.get(request, path)
添加url路由配置
from django.conf import settings
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.static import serve
from common.celery.flower import CeleryFlowerView
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'api/flower/(?P<path>.*)', CeleryFlowerView.as_view(), name='flower-view'),
# media路径配置 开发环境可以启动下面配置,正式环境需要让nginx读取资源,无需进行转发
re_path('^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
]
可以看到上面代理使用了额外的认证配置,是因为flower2.0 中部分操作,需要认证才能操作
3.启动flower进程
celery -A server flower -logging=info --url_prefix=/api/flower --basic-auth=flower:flower123. --address=127.0.0.1 --port=5566
4.访问
可以看到,cookie信息已经传递到后台,然后基于token进行认证