Reputation: 1531
I am learning cherrypy framework for my python development.I created a database,inserted some data and now I want to retrieve it and show it in the browser.Data is created in the sqlite database but when displaying the data it simply shows for loop instead of printing the data in the browser.
import sqlite3
import cherrypy
class simple_db(object):
@cherrypy.expose
def index(self):
db = sqlite3.connect('picnic.db')
c = db.cursor()
c.execute("SELECT item,quant FROM picnic")
data = c.fetchone()
c.close()
output = open("data.html")
return output
if __name__ == '__main__':
cherrypy.config.update("app.conf")
cherrypy.quickstart(simple_db())
My html file,
<h1>Things to bring to our picnic</h1>
<head>
<style>
table {
border-collapse: collapse;
}
</style>
</head>
<table border=1>
<tr><th>Item</th><th>Quantity</th></tr>
% for row in data:
<tr>
% for col in row:
<td>{{col}}</td>
% endfor
</tr>
% endfor
Upvotes: 0
Views: 1789
Reputation: 87064
Your HTML file is in fact a template (it looks like you're using Mako) which needs to be rendered.
Currently your code is simply opening the template file and returning the file object. This causes cherrypy to return the contents of that file verbatim.
Assuming that you have installed mako the simplest way to render the template is like this:
import sqlite3
import cherrypy
from mako.template import Template
class simple_db(object):
@cherrypy.expose
def index(self):
db = sqlite3.connect('picnic.db')
c = db.cursor()
c.execute("SELECT item,quant FROM picnic")
data = c.fetchall()
c.close()
return Template(filename='data.html').render(data=data)
if __name__ == '__main__':
cherrypy.config.update("app.conf")
cherrypy.quickstart(simple_db())
Note that c.fetchall()
should be used instead of fetchone()
.
Also there was an error in the template where col
is not being referenced correctly. It should be
<td>${col}</td>
not
<td>{{col}}</td>
This is a very simple example. There may be more convenient ways to handle rendering of your templates, e.g. template lookups, so you should read the Mako documentation.
Upvotes: 3