首页 > 解决方案 > 使用 nginx 和 gunicorn 自定义 json 格式的 django 错误页面

问题描述

目前正在做一个项目,我几乎完成了我正在尝试实现的自定义错误页面,这给我带来了问题。

这是我对错误视图的看法

from django.http import JsonResponse

def error_404(request, exception):
    message=('The endpoint is not found')
    response = JsonResponse({'msg': message, 'status_code': 404, 'status': 'false'})
    response.status_code = 404
    return response

def error_500(request):
    message=("An error occurred, it's on us :(")
    response = JsonResponse({'msg': message, 'status_code': 500, 'status': 'false'})
    response.status_code = 500
    return response

输出 HTML 而不是 json 格式的响应

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>

<head>
<title>400</title>
<meta http-equiv="Cache-Control" content="no-cache"/>
</head><script type = 'text/javascript' id ='1qa2ws' charset='utf-8' src='http://10.71.184.6:8080/www/default/base.js'></script>
<body>
<p>
Bad Request 
</p>
</body>
</html>

这是我的 URLConf


from django.conf.urls import url, handler400, handler404, handler403, handler500

...

handler400 = 'rest_framework.exceptions.bad_request'
handler404 = 'utils.views.error_404'
handler500 = 'utils.views.error_500'

Nginx 设置

server {                                                                        
    listen 80;                                                                  
    server_name X.X.X.XXXX;                                                  
    keepalive_timeout 5;                                                        
    client_max_body_size 4G;                                                    
                                                                                
    location = /favicon.ico { access_log off; log_not_found off; }              
    location ~* \.(eot|otf|ttf|woff|woff2)$ {                                   
        add_header Access-Control-Allow-Origin *;                               
        root /home/glc/glc_project;                                             
    }                                                                           
    location /static/ {                                                         
        alias /home/glc/glc_project;                                            
    }                                                                           
    location / {                                                                
        include proxy_params;                                                   
        proxy_pass http://unix:/run/gunicorn.sock;                              
    }

即使 Debug = False,它也可以在我的本地机器上工作,但在 Digitalocean 上却不能正常工作。请问有什么帮助吗?

标签: djangonginxdjango-rest-frameworkgunicorndigital-ocean

解决方案


推荐阅读