首页 > 解决方案 > Django 502 bad gateway 导致多封电子邮件发送

问题描述

我有一个正在运行的带有 uwsgi 的 Django 应用程序,由 nginx 提供服务。我用于许多应用程序的相同环境(https://github.com/abidibo/cookiecutter-django)。我已将 Postfix 配置为在 localhost 上接收,并将 Django 配置为通过它发送电子邮件。

我有一个观点,当收到一个 POST 请求时,它会创建一些文件并发送一封电子邮件。

发生的情况是,服务器在处理完 POST 请求后,返回了 502 页面,并且发送了多封电子邮件(将近 60 封电子邮件)。它不会每次都发生,只是几次,而且我无法在本地环境中重现该错误。

我不知道发生了什么,我的意思是,如果 Django 和 uwsgi 或 postfix 本身之间发生了超时,那么为什么要发送所有这些电子邮件,为什么代码会被多次执行?

在应用程序日志中,我看到一名工人死亡:

- *** HARAKIRI ON WORKER 4 (pid: 8836, try: 1) ***
- HARAKIRI !!! worker 4 status !!!
- HARAKIRI [core 7] 188.92.61.228 - POST /xxx/xxx/xxx/4/ since 1549027535
- HARAKIRI !!! end of worker 4 status !!!
DAMN ! worker 4 (pid: 8836) died, killed by signal 9 :( trying respawn ...
Respawned uWSGI worker 4 (new pid: 21942)

在 nginx 错误日志中,我看到:

 [error] 2565#2565: *19983 upstream prematurely closed connection while reading response header from upstream, client: xx.xx.xx.xx, server: xxx.xxx.com, request: "POST /xxx/xxx/xx/4/ HTTP/1.1", upstream: "uwsgi://unix:/tmp/uwsgi_xxx.sock:", host: "xxx.xxx.com", referrer: "http://xxx.xxx.com/xxx/xxx/xx/4/"

更新

这是post view函数的摘录

def post(self, request, pk):
# stuff...
    try:
    # stuff...
        if request.POST.get('send_mail', False) and request.POST.get(
                'destinatari', ''):
            send_invoice_mail(fattura, [
                e.strip()
                for e in request.POST.get('destinatari', '').split(',')
            ])

        messages.add_message(
            request, messages.SUCCESS,
            'Nota di Credito cliente generata con successo')
        messages.add_message(
            request, messages.SUCCESS,
            'La nota di credito è stata correttamente inserita in prima nota'
        )
        if request.POST.get('send_mail', False):
            messages.add_message(request, messages.SUCCESS,
                                 'E-mail correttamente inviata')

        return redirect('/admin/fatture/notacreditouscitacliente/')

    except Exception as e:
        # stuff...
        messages.add_message(request, messages.WARNING, str(e))
        return redirect(
            '/admin/fatture/notacreditoentratafornitoreprodotti')

我该如何调试呢?

标签: djangouwsgipostfix-mtabad-gateway

解决方案


推荐阅读