如何在web.py中按列返回sqlite3表

时间:2017-03-09 08:25:51

标签: python sqlite web.py

我正在练习web.py.在Web服务器中,我有一个sqlite3数据库,我想通过http访问返回其记录。如何在browerse中的每条记录之间添加换行符?

以下是我在浏览器中获得的内容,我希望在每个rocord之间添加换行符,例如:

[('2017-02-23 10:19:13', 1.68, 1.01),     
('2017-02-23 10:19:51', 1.03, 1.9),     
('2017-02-23 10:21:41', 1.97, 1.6),     
('2017-02-23 10:22:39', 1.57, 1.75),

我的代码如下:

import web
import sqlite3

render = web.template.render('templates/')

urls = (
    '/', 'index'
)


class index:
    def GET(self):
        conn = sqlite3.connect('customer-01.db')
        cursor = conn.execute("SELECT *  from datasource")
        return cursor.fetchall()

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()

enter image description here

1 个答案:

答案 0 :(得分:0)

您的return cursor.fetchall()会返回显示在浏览器中但没有任何特殊格式的文字 - 这就是为什么它是一条长行。

要让它在浏览器中看起来更好,请返回HTML。然后,您可以在每一行之间添加<br/>(或将其格式化为表格或,或......)

您可以使用web.py模板,但由于您要保持简单,所以您需要做的就是显式设置Content-Type并添加一些HTML。

更新你的GET:

def GET(self):
    conn = sqlite3.connect('customer-01.db')
    cursor = conn.execute("SELECT * from datasource")
    web.header('Content-Type', 'text/html')    # you're sending HTML rather than text
    ret = [str(x) for x in cursor.fetchall()]  # Convert each row to string
    return '<br/>'.join(ret)                   # return single string, with <br/> between rows