如何从sqlite返回值web?

时间:2015-04-07 12:45:12

标签: python sqlite wsgi

这是我的代码。我想在网上展示这些价值观。怎么会这样呢?

import sqlite3

def application(environ, start_response):

 db = sqlite3.connect('/root/example.db')
 db.row_factory = sqlite3.Row
 cursor = db.cursor()
 cursor.execute('''SELECT id, message,date FROM table''')
 for row in cursor:
  print('{0} : {1}, {2}'.format(row['id'], row['message'], row['date']))
 db.close()

 start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])

1 个答案:

答案 0 :(得分:0)

构建要返回的字符串列表;打印写入stdout并且不会返回到浏览器。

db = sqlite3.connect('/root/example.db')
db.row_factory = sqlite3.Row
cursor = db.cursor()
cursor.execute('''SELECT id, message,date FROM table''')

results = []
for row in cursor:
    results.append('{0} : {1}, {2}'.format(row['id'], row['message'], row['date']))
db.close()


headers = [
    ('Content-Type', 'text/html; charset=utf-8'),
    ('Content-Length', str(sum(len(line) for line in results)))
]

start_response('200 OK', headers)

return results