WSGI 应用如何让web服务器发送默认的HTTP 404错误页面?
我有一个简单的WSGI应用程序,放在一个叫做app
的模块里(app.py),它的样子是这样的:
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响应发送给客户端呢?
注意:
- 我希望这个解决方案不依赖于特定的网络服务器,也就是说,我不想在代码或模板中硬编码网络服务器的HTTP 404页面,或者读取一些非常特定于nginx的HTML。这个解决方案应该在nginx或其他任何网络服务器上都能工作,比如Apache、lighttpd等。
- 我知道应该使用WSGI框架来进行实际的网页开发。我可能会选择使用bottle.py,但在此之前,我想了解WSGI的能力和局限性,这样我在使用bottle时就能明白背后发生了什么。
2 个回答
0
看看uWSGI和nginx一起使用时是否支持:
如果它在原生协议下不支持这个功能,你可能需要把uWSGI设置成HTTP接收模式,然后通过HTTP使用普通的nginx代理模式。这样你就可以使用它了。
无论如何,去IRC的#uwsgi频道找unbit问问吧。很可能在你还没聊完的时候,他们就会把这个功能加上。他就是这样的人。
2
从评论区的讨论来看,答案似乎是:
不可以!