Skip to main content
 首页 » 编程设计

python之WSGI 应用程序能否告诉为其服务的 Web 服务器发送其默认的 HTTP 404 错误页面

2025年05月04日37zhwl

我在名为 app (app.py) 的模块中有一个裸 WSGI 应用程序,如下所示:

def application(environ, start_response): 
    path = environ['PATH_INFO'] 
    if path == '/': 
        start_response('200 OK', [('Content-Type','text/html')]) 
        return [b'<p>It works!</p>\n'] 
    elif path == '/foo': 
        start_response('200 OK', [('Content-Type','text/html')]) 
        return [b'<p>Hello World</p>\n'] 
    else: 
        start_response('404 Not Found', [('Content-Type','text/html')]) 
        return [b'<p>Page Not Found</p>\n'] 

我正在使用具有此配置的 nginx + uwsgi 为这个应用程序提供服务。

nifty:/www# cat /etc/nginx/sites-enabled/myhost 
server { 
        listen 8080; 
        root /www/myhost; 
        index index.html index.htm; 
        server_name myhost; 
    location / { 
        uwsgi_pass 127.0.0.1:9090; 
        include uwsgi_params; 
    } 
} 

我用这个命令启动 uwsgi:

uwsgi --socket 127.0.0.1:9090 --module app 

应用的行为符合预期:

debian:~# curl -i http://myhost:8080/ 
HTTP/1.1 200 OK 
Server: nginx/1.4.4 
Date: Mon, 24 Mar 2014 13:05:51 GMT 
Content-Type: text/html 
Transfer-Encoding: chunked 
Connection: keep-alive 
 
<p>It works!</p> 
debian:~# curl -i http://myhost:8080/foo 
HTTP/1.1 200 OK 
Server: nginx/1.4.4 
Date: Mon, 24 Mar 2014 13:05:55 GMT 
Content-Type: text/html 
Transfer-Encoding: chunked 
Connection: keep-alive 
 
<p>Hello World</p> 
debian:~# curl -i http://myhost:8080/bar 
HTTP/1.1 404 Not Found 
Server: nginx/1.4.4 
Date: Mon, 24 Mar 2014 13:05:58 GMT 
Content-Type: text/html 
Transfer-Encoding: chunked 
Connection: keep-alive 
 
<p>Page Not Found</p> 

但是,我对 HTTP 404“找不到页面”响应不满意。我希望当我的 WSGI 应用程序想要发送 HTTP 404 响应时,nginx 的默认 HTTP 404 错误页面被发送到客户端。

这是 nginx 默认的 HTTP 404 响应的样子。请注意,下面的响应来自默认虚拟主机(不是上面示例中使用的 myhost 虚拟主机)。默认虚拟主机没有任何 WSGI 应用程序,因此您可以在下面的输出中看到 nginx 的默认 HTTP 404 错误页面。

debian:~# curl -i http://localhost:8080/bar 
HTTP/1.1 404 Not Found 
Server: nginx/1.4.4 
Date: Mon, 24 Mar 2014 13:06:06 GMT 
Content-Type: text/html 
Content-Length: 168 
Connection: keep-alive 
 
<html> 
<head><title>404 Not Found</title></head> 
<body bgcolor="white"> 
<center><h1>404 Not Found</h1></center> 
<hr><center>nginx/1.4.4</center> 
</body> 
</html> 
debian:~# 

我的 WSGI 应用程序有没有办法告诉为其服务的网络服务器将其 HTTP 404 响应发送给客户端?

注意:

  1. 我希望解决方案与网络服务器无关,即我不必在我的代码或模板中对网络服务器的 HTTP 404 页面进行硬编码,或者我不必阅读一些非常具体的 HTML到 nginx。该解决方案应适用于 nginx 或任何其他网络服务器,如 Apache、lightttpd 等。
  2. 我知道应该使用 WSGI 框架来进行实际的网络开发。我可能会选择 bottle.py,但在此之前,我会尝试了解 WSGI 的功能和局限性,以便我了解使用 bottle 时幕后发生的事情。

请您参考如下方法:

从评论区的讨论来看,答案好像是:

不!