0

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this solved my problem,Can u explain what is meant by name='__main'?
@Bhanukiran: no problem. You can find out about __main__ in the documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.