502 Django、nginx、DigitalOcean、Gunicorn中存在严重网关错误,但只是偶尔出现

2024-05-16 00:17:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在与Gunicorn、Nginx、Postgres一起开发部署在DigitalOcean上的Django应用程序。一切都很好,但我遇到了一个奇怪的问题502 Bad Gateway,只有在我使用xhtml2pdf生成PDF时才会遇到

然而,这个问题并不是一成不变的,它只是偶尔出现。我的Nginx和Gunicorn超时设置为30秒,但错误出现在30秒之内

这是我生成PDF的代码

def link_callback(uri, rel):
    # use short variable names
    sUrl    = settings.STATIC_URL      # Typically /static/
    sRoot   = settings.STATIC_ROOT    # Typically /home/userX/project_static/
    mUrl    = settings.MEDIA_URL       # Typically /static/media/
    mRoot   = settings.MEDIA_ROOT     # Typically /home/userX/project_static/media/

    # convert URIs to absolute system paths
    if uri.startswith(mUrl):
        path = os.path.join(mRoot, uri.replace(mUrl, ""))
    elif uri.startswith(sUrl):
        path = os.path.join(sRoot, uri.replace(sUrl, ""))

    # make sure that file exists
    if not os.path.isfile(path):
        raise Exception('media URI must start with %s or %s' % (sUrl, mUrl))
    return path

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html     = template.render(context_dict)
    result   = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result, link_callback=link_callback)
    if not pdf.err:
        if for_mail:
            return result.getvalue()
        else:
            return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

我还在生成的PDF上显示徽标,因此使用了link_callback函数

我不认为问题出在Nginx或gunicorn的配置文件上,因为它应该一直工作,或者根本不工作。此外,只有当我将HTML转换为PDF时,问题才会出现,而不是在任何其他部分

直到昨天,天气一直很好。我不知道出了什么问题。任何帮助都将不胜感激


Tags: pathreturnifsettingspdfcallbacklinkstatic