2013-02-27 71 views
0

我使用BaseHttpServer设置了一个基本的python webserver,并且正在从postgresql数据库中查询数据。一切都在顺利进行,但是当我解析SQL结果时,我遇到了一个错误。 这里是我的代码:TypeError:'datetime.timedelta'对象不可迭代 - BaseHttpServer问题

cur=con.cursor() 
cur.execute(('select * from stop_times as a, stop_times as b where a.train_id=b.train_id and a.station_name = %s and b.station_name= %s and a.arrival_time < b.arrival_time'), (origin_name, dest_name)) 

self.wfile.write("Train Number &nbsp &nbsp Starting Station &nbsp &nbsp Destination Station &nbsp &nbsp Departure Time &nbsp &nbsp Arrival Time <br />") 

while True: 
    row=cur.fetchone() 
    if row==None: 
     break 

    print row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8] 

    for item in row[0]: 
     self.wfile.write("%s"% item) 
    self.wfile.write(" &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp") 
    for item in row[3]: 
     self.wfile.write("%s"% item) 
    self.wfile.write(" &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp") 

    for item in row[8]:       
     self.wfile.write("%s"% item) 
    self.wfile.write("&nbsp &nbsp &nbsp &nbsp") 

    for item in row[2]: 
     self.wfile.write("%s"% item) 
    self.wfile.write("&nbsp &nbsp") 

print语句是有调试到控制台,并给出了正确的输出:

427 10:23:00 10:23:00 San Antonio 6 427 11:08:00 11:08:00 Millbrae 
429 11:23:00 11:23:00 San Antonio 6 429 12:08:00 12:08:00 Millbrae 
431 12:23:00 12:23:00 San Antonio 6 431 13:08:00 13:08:00 Millbrae 

我只是想输出特定的列到网上页面,当我到达那个最后的for循环行[2]我得到这个错误:

File "./caltrainServer.py", line 129, in performQuery 
for item in row[2]: 
TypeError: 'datetime.timedelta' object is not iterable 

我查了一下,在我的数据库中的那些列的类型都是间隔。我如何像遍历其他列的类型varchar一样遍历它们?

+0

'row [2]'是'datetime.timedelta',你不能从它内部获得'item'(因为它只有它自己)。我不认为你需要做任何迭代,你可以''self.wfile.write(“{0},{1} ... {9}”.format(row [0],row [1])。 .. row [9]))'? – GordonsBeard 2013-02-27 00:48:03

+0

您是否打算使用html实体' '(而不是'&nbsp')? – 2013-02-27 00:52:45

+0

啊,是的,我应该输入  – 2013-02-27 00:54:38

回答

2

您不必要地遍历行值的内容。行这样的:

for item in row[0]: 
    self.wfile.write("%s"% item) 

有可能成为改变

self.wlfile.write(row[0]) 

你在做什么,当row[x]是一个字符串实际上是遍历每个字母,写它。但是row[2]是一个datetime.datetime对象。并且由于datetime.datetime对象不可迭代,所以您会收到该错误消息。

尝试,而不是像这样:

self.wlfile.write((row[2])) 

这会将DateTime对象中,可以重复的元组。