Python在Apache2上的404错误

1 投票
2 回答
2002 浏览
提问于 2025-04-16 15:28

我在 /var/www 目录下有一个文件 test.py,我在使用 Ubuntu 10.10 上的 apache2。我已经安装了 mod_python,并且配置了 /etc/apache2/sites-available/default,内容如下:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride AuthConfig
    Order allow,deny
    allow from all

    AddHandler mod_python .py
    PythonHandler mod_python.publisher
    PythonDebug On

    # Uncomment this directive is you want to see apache2's
    # default start page (in /apache2-default) when you go to /
    #RedirectMatch ^/$ /apache2-default/
</Directory>

如果我放入:

def index(req):
  return "Test successful";

那么我会看到 Test successful

但是如果我放入:

#!/usr/bin/env python
print "Content-Type: text/html"
print
print """\
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
"""

我就会收到 404: Not found 的错误。

更多信息可以在 这里找到。

有没有人有什么想法呢?

祝好,

experimentX

2 个回答

1

与其使用 mod_python,我建议你用 mod_wsgi。因为有很多使用 WSGI 的框架,比如 FlaskCherryPyBottle 等等。

这些框架的一个好处是,你在开发的时候根本不需要在你的电脑上使用 Apache,而是可以直接用它们自带的测试服务器。

2

mod_python 默认会寻找一个叫做 def index(req) 的方法来处理你的请求。如果你想调用其他的函数,可以在网址中指定那个函数。需要注意的是,那个函数必须返回一个特定的值。

所以你可以这样做:

s ="""\
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
"""

def index():
   return s

在 mod_python 中,网址的访问方式可以在 这里查看。

撰写回答