我在一个名为
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:~
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:~
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:~
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“Page not Found”响应不满意。我希望当我的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应用程序是否有方法告诉服务它的web服务器向客户端发送其HTTP 404响应?
注:
-
我希望解决方案不受web服务器的限制,即我不必在代码或模板中硬编码web服务器的HTTP 404页面,或者我不必阅读某些特定于nginx的HTML。该解决方案应在nginx或任何其他web服务器(如Apache、lightttpd等)上运行。
-
我知道应该使用WSGI框架来进行实际的web开发。我可能会选择瓶装水,但在这样做之前,我正在尝试了解WSGI的功能和局限性,以便我知道在使用瓶装水时幕后发生了什么。