Python程序出现500未定义索引页

2 投票
3 回答
603 浏览
提问于 2025-04-17 22:54

我刚在看Python的教程时,复制并跟着做了这个应用。

http://www.mongodb.com/presentations/building-web-applications-mongodb-introduction

文件结构如下:

./app
 ├── views/
 │     ├── index.tpl
 ├── index.py
 └── guestbookDAO.py

index.py

import bottle
import pymongo
import guestbookDAO

#This is the default route, our index page.  Here we need to read the documents from MongoDB.
@bottle.route('/')
def guestbook_index():
    mynames_list = guestbook.find_names()
    return bottle.template('index', dict(mynames = mynames_list))

#We will post new entries to this route so we can insert them into MongoDB
@bottle.route('/newguest', method='POST')
def insert_newguest():
    name = bottle.request.forms.get("name")
    email = bottle.request.forms.get("email")
    guestbook.insert_name(name,email)
    bottle.redirect('/')


#This is to setup the connection

#First, setup a connection string. My server is running on this computer so localhost is OK
connection_string = "mongodb://localhost"
#Next, let PyMongo know about the MongoDB connection we want to use.  PyMongo will manage the connection pool
connection = pymongo.MongoClient(connection_string)
#Now we want to set a context to the names database we created using the mongo interactive shell
database = connection.names
#Finally, let out data access object class we built which acts as our data layer know about this
guestbook = guestbookDAO.GuestbookDAO(database)

bottle.debug(True)
bottle.run(host='localhost', port=8082) 

guestbookDAO.py

import string

class GuestbookDAO(object):

#Initialize our DAO class with the database and set the MongoDB collection we want to use
    def __init__(self, database):
        self.db = database
        self.mynames = database.mynames

#This function will handle the finding of names
    def find_names(self):
        l = []
        for each_name in self.mynames.find():
            l.append({'name':each_name['name'], 'email':each_name['email']})

        return l

#This function will handle the insertion of names
    def insert_name(self,newname,newemail):
        newname = {'name':newname,'email':newemail}
        self.mynames.insert(newname)

index.tpl

<!DOCTYPE html>
<html>
<head>
    <title>Welcome to MongoDB</title>
    <style type="text/css">
        body{font-family:sans-serif;color:#4f494f;}
        form input {border-radius: 7.5px;}
        h5{display: inline;}
        .label{text-align: right}
        .guestbook{float:left;padding-top:10px;}
        .name{width:100%;float:left;padding-top: 20px}
    </style>
</head>
<body>

<div class="wrapper">
    <h1>Welcome To MongoDB!</h1>
    <div class="guestbook_input">
        <form method="post" class="form" action="/newguest">
            Name: <input type="text" name="name"/>
            Email: <input type="text" name="email"/>
            <input type="submit" value="Add Guest"/>
        </form>
    </div>

    <div class="guestbook">
        <h3>Guests:</h3>
        %for name in mynames:
            <div class="name">
                <h5>Name:</h5> {{name['name']}},
                <h5>Email:</h5> {{name['email]']}}
            </div>
        %end
    </div>
</div>




</body>
</html>

我在路由或模板定义上做错了什么,导致出现这个问题呢?

3 个回答

2

你的模板里有个拼写错误。把:

<h5>Email:</h5> {{name['email]']}}

换成:

<h5>Email:</h5> {{name['email']}}

希望这能帮到你。

3

你需要在 TEMPLATE_PATH 中添加你模板文件的绝对路径:

bottle.TEMPLATE_PATH.insert(0,'/absolut/path/to/your/templates/')

关于找不到Bottle模板的问题(常见问题解答):

Bottle会在当前目录(./)和当前目录下的views文件夹(./views/)中寻找模板。在mod_python或mod_wsgi环境中,当前工作目录(./)是根据你的Apache设置决定的。

所以你需要把 index.py 改成:

import os
# Add these lines before `bottle.run` line.
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
template_path = os.path.join(BASE_DIR, 'views')
bottle.TEMPLATE_PATH.insert(0, template_path)
...
...
bottle.debug(True)
bottle.run(host='localhost', port=8082) 

注意:如果你从项目的根目录运行 python index.py

mongoguestbook$ ls -la
 guestbookDAO.py
 guestbookDAO.pyc
 index.py
 README.md
 views
mongoguestbook$ python index.py

那么你就不需要在 index.py 中添加上面的代码,因为 bottle.TEMPLATE_PATH 的默认值,如常见问题解答中所述是:

print(bottle.TEMPLATE_PATH)
# ['./', './views/'])

但是如果你添加了这些代码,那么你可以从根目录 $ python index.py 运行,或者从任何地方运行: $ python ~/workspace/so/mongoguestbook/index.py

2

尝试在同一个文件夹里运行 index.py,比如你可以输入 python index.py 来运行,不要输入 python /same/directory/index.py 来运行。

我也遇到过这个问题。

撰写回答