羣聊的前臺主要代碼:
{%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+1
self.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,新消息提示,都是前端的東西,在基本功能全部實現後加上去。
轉載請註明:轉自http://blog.csdn.net/littlethunder/article/details/25560003