【问题标题】:How to use python code inside html file in cherrypy framework?如何在cherrypy框架的html文件中使用python代码?
【发布时间】:2016-03-31 12:05:22
【问题描述】:

我正在为我的python开发学习cherrypy框架。我创建了一个数据库,插入了一些数据,现在我想检索它并在浏览器中显示它。数据是在sqlite数据库中创建的,但是在显示数据时它只是显示for 循环而不是在浏览器中打印数据。

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())

我的 html 文件,

    <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

【问题讨论】:

    标签: python python-2.7 cherrypy


    【解决方案1】:

    您的 HTML 文件实际上是一个需要渲染的模板(看起来您正在使用Mako)。

    目前您的代码只是打开模板文件并返回文件对象。这会导致cherrypy逐字返回该文件的内容。

    假设你已经安装了mako,最简单的渲染模板的方式是这样的:

    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())
    

    请注意,应使用c.fetchall() 而不是fetchone()

    模板中也有一个错误,col 没有被正确引用。应该是

            <td>${col}</td>
    

    不是

            <td>{{col}}</td>
    

    这是一个非常简单的例子。可能有更方便的方法来处理模板的呈现,例如模板查找,所以你应该阅读Mako documentation

    【讨论】:

    • 谢谢这解决了我的问题,你能解释一下name='__main'是什么意思吗?
    • @Bhanukiran:没问题。您可以在documentation 中找到有关__main__ 的信息。
    猜你喜欢
    • 1970-01-01
    • 2016-11-03
    • 2023-03-20
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 2012-04-10
    • 2020-04-17
    相关资源
    最近更新 更多