群聊的前台主要代碼:
{%block content%}<!--<p class='text-success h3'>測試版本,每天淩晨4:00清水,enjoy it~~:-)</p>--><ul>{%for i in content[19*int(num)-19:19*int(num)]%}<li class='text-info'><a href='/user/{{i[1]}}' class='text-success h4'>【{{i[1]}}】</a> ({{i[3]}}) : {{i[2]}}</li>{%end%}</ul><ul class='pagination'>{%for i in range(1,pages+1)%}<li {%if int(num)==i%}class='active'{%end%}><a href='/chat/{{i}}'>{{i}}</a></li>{%end%}</ul></br></br><form action='/chat/1' method='post' class='well form-search'><label class='sr-only'>發表新貼</label><input type='text' name='topic' placeholder='發表新貼...'/><button type='submit' class='btn btn-danger'>發送</button></form>{%end%}
後台代碼:
class chatHandler(tornado.web.RequestHandler):def get(self,num): #num第幾頁name=self.get_cookie('hackerName')chats=showChat()n=len(chats)if n%20==0:pages=n//20 #pages總頁數else:pages=n//20+1self.render('chat.html',cookieName=name,content=chats,pages=pages,num=num)def post(self,num):name=self.get_cookie('hackerName')if not name:return #在javascript 中判斷是否已登入newTopic=self.get_argument('topic')insertChat(name,newTopic)self.redirect('/chat/1')
showChat函數定義如下:
def showChat():c.execute('select * from chat')tmp=c.fetchall()return tmp[::-1] #逆序,最新貼放在最上面
insertChat函數定義如下:
def insertChat(name,content):now=getTime()c.execute('insert into chat(name,content,time) values("'+name+'","'+content+'","'+now+'")')db.commit()
如下:
群聊內容是按時間逆序排的,最新的在最上面,滿20條就增加一頁,預設的群聊首頁就是/chat/1,即第一頁。這裡實現的只是準系統,之後還要加上即時重新整理ajax,新訊息提示,都是前端的東西,在準系統全部實現後加上去。
轉載請註明: