2013-10-05 23:04:33|
1. web.py 使用 db.select 返回的数据只能遍历一次
import web
db = web.database(dbn='mysql', db='test', user='root', pw='123456')
results = db.query("SELECT * FROM user where username='lily'")
print type(results)
print "results[0][2]:",results[0].password
print type(results[0].password)
for r in results:
print r
import web
db = web.database(dbn='mysql', db='test', user='root', pw='123456')
results = db.query("SELECT * FROM user where username='lily'")
print type(results)
print "results[0][2]:",results[0].password
print type(results[0].password)
for r in results:
print r
报错:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print type(results[0].password)
File "/usr/local/lib/python2.7/dist-packages/web/utils.py", line 536, in __getitem__
raise IndexError, "already passed "+str(i)
IndexError: already passed 0
解决:
参考资料:http://segmentfault.com/q/1010000000095518
Python 中的迭代器本来就是一次性的,无论是生成器表达式还是 yield 都是这样。如果你需要多次使用,应该先用 list 工厂函数将迭代器转换成列表。当然,转换之后迭代器就空了,但是数据保存到了列表中。