django 中长连接的实现方法

最近做一个项目,客户端要进行实时的邮件提醒,那就做一个ajax long polling吧,因为没有太多的处理,用celery实在是大材小用。

django的orm似乎对长连接不支持,在一个请求request中,无论读多少次数据库,queryset的值都不变,不知作者是出于什么考虑,将查询写死在了一次请求之中,没办法,只好用python了,python的cursor还是很好用的,果然,成功了。

附部分代码

t=20
while t>0:
if answer_count!=int(count1) or mail_count!=int(count2):
mail=Send.objects.filter(userto=user,unreadcount__gt=0)
data=[]
data.append({'answer_count':int(answer_count)})
data.append({'mail_count':int(mail_count)})
for x in mail:
data.append({'firstname':x.userfrom.first_name,'lastname':x.userfrom.last_name})
cxn.close()
return HttpResponse(simplejson.dumps(data))
else:
cur.execute('select sum(unreadcount) from letter_send where userto_id='+str(user.id))
mail_count=cur.fetchone()[0]
cxn.commit()
cur.execute('select sum(reply_not_read) from questions_problem where user_id='+str(user.id))
answer_count=cur.fetchone()[0]
cxn.commit()
time.sleep(2)
t-=1
cxn.close()

原文地址:https://www.cnblogs.com/lddhbu/p/2601723.html