سؤال

I was just looking through Python tutorials when I copied and followed this app

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

file structure is follow:

./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>

What am I doing wrong for the routing or template definition that's causing this issue?

هل كانت مفيدة؟

المحلول 2

try run index.py in the same directory, example, run python index.py, don't run python /same/directory/index.py

this problem happened me

نصائح أخرى

You should add an absolute path of your template location to the TEMPLATE_PATH:

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

Bottle Template Not Found(FAQ):

Bottle searches in ./ and ./views/ for templates. In a mod_python or mod_wsgi environment, the working directory (./) depends on your Apache settings.

So change index.py to:

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) 

Note: if you run python index.py from root of your project:

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

Then you don't need to add above codes to index.py, because the default value of bottle.TEMPLATE_PATH as descibed in FAQ is:

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

But if you add them, then you can run it from root $ python index.py or from anywhere: $ python ~/workspace/so/mongoguestbook/index.py.

You have a typo in the template. Replace:

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

with:

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

Hope that helps.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top