【问题标题】:How to return the table of sqlite3 by column in web.py如何在web.py中按列返回sqlite3的表
【发布时间】:2026-02-16 20:40:01
【问题描述】:

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

这是我在浏览器中得到的,我想在每个 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()

【问题讨论】:

  • 嗨乔,欢迎来到 Stack Overflow!为了帮助人们回答您的问题,您能否提供给我们minimal reproducible example?这样我们就可以看到您的尝试,并就最佳行动方案为您提供建议。干杯!

标签: python sqlite web.py


【解决方案1】:

您的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

【讨论】:

    最近更新 更多