Python使用django框架實(shí)現(xiàn)多人在線匿名聊天的小程序
最近看到好多設(shè)計(jì)類網(wǎng)站,都提供了多人在線匿名聊天的小功能,感覺(jué)很有意思,于是基于python的django框架自己寫(xiě)了一個(gè),支持手動(dòng)實(shí)時(shí)更名,最下方提供了完整的源碼.
在線聊天地址(無(wú)需登錄,開(kāi)一個(gè)窗口,代表一個(gè)用戶):
http://zhaozhaoli.vicp.io/chatroom/happy/
移動(dòng)端聊天效果圖:
網(wǎng)頁(yè)版聊天效果圖:
實(shí)現(xiàn)思路:
發(fā)送的消息通過(guò)ajax先寫(xiě)入數(shù)據(jù)庫(kù),通過(guò)ajax的循環(huán)請(qǐng)求,將寫(xiě)入數(shù)據(jù)庫(kù)的消息顯示到前端界面.
前端核心代碼:
<script> $(function () { $("#send").click(function () { var input_info = $("#input_info").val(); if (input_info.length < 1) { alert("請(qǐng)輸入字符后發(fā)送"); return; } else if (input_info.length > 200) { alert("每次發(fā)送不可以超出200個(gè)字符哈~"); return; } else { // 獲取csrftoken的值 var csrf_value = $('#csrfmiddlewaretoken').text(); var user_id = $("#user_id").text(); var user_name = $("#user_name").text(); $.ajax({ 'url': '/chatroom/save_chat_log/', 'data': { 'chat_content': input_info, 'user_id': user_id, 'user_name': user_name, 'user_ip': '127.127.127.127', 'csrfmiddlewaretoken': csrf_value }, 'type': 'post', 'async': false, 'success': function (data) { } }); $("#input_info").val(""); console.log($("#show_info").scrollTop()); } }) }) </script> <script> var user_id = $("#user_id").text(); var user_name = $("#user_name").text(); $(function () { var last_id = 0; var csrf_value2 = $('#csrfmiddlewaretoken').text(); function update_info() { // ajax 獲取最新數(shù)據(jù) $.ajax({ 'url': '/chatroom/get_near_log/', 'data':{"last_id":last_id,'csrfmiddlewaretoken': csrf_value2}, 'type':'post', 'async': false, 'success':function (data) { if (parseInt(last_id) == parseInt(JSON.parse(data.data).last_id)){ return; } //獲取后臺(tái)傳過(guò)來(lái)的id值,并將值存儲(chǔ)到全局變量中 last_id = JSON.parse(data.data).last_id; // 將內(nèi)容讀取,并打印 content = JSON.parse(data.data).info; for (var i=0; i< content.length; i++){ if (parseInt(content[i].user_id) == parseInt($("#user_id").text())){ var html = "<div class='my_info'><span>"+content[i].user_name+"</span></div>"; html = html + "<div class='my_one_info'>"+content[i].mess+"</div>"; $("#content").append(html); }else{ var html = "<div class='other_info'><span>"+content[i].user_name+"</span></div>"; html = html + "<div class='other_one_info'>"+content[i].mess+"</div>"; $("#content").append(html); } $("#show_info").scrollTop($("#content").height()) } } }) } update_info(); setInterval(update_info, 1000); }) </script> <script> $(function () { //監(jiān)聽(tīng)鍵盤點(diǎn)擊 $(document).keyup(function (event) { if (event.keyCode == 13){ $("#send").click(); } }) }) </script> <script> $(function () { $("#change_name").click(function () { // 獲取新名稱 var new_name = String($("#new_name").val()); // 檢查新名稱是否合法 // 如果合法 if (new_name.length<11 && new_name.length>0){ console.log(new_name); $("#user_name").text(new_name); $("#new_name").val("") }else{ alert("昵稱長(zhǎng)度應(yīng)為1-10,請(qǐng)重新輸入"); $("#new_name").val("") } }) }) </script> <div id="main_form"> <div class="my_nike_name">我的昵稱:<span id="user_name">{{user_name}}</span><span><button id="change_name">更名</button><input type="text" id="new_name"></span></div> <div id="show_info"> <div id="content"> </div> </div> <br> <div class="my_nike_name">消息</div> <input type="text" id="input_info"> <button id="send">發(fā)送消息</button> <div id="user_id" style="display: none">{{user_id}}</div> <div id="user_ip" style="display: none">{{user_ip}}</div> <span id ="csrfmiddlewaretoken" style="display: none">{{csrf_token}}</span> </div>
后端核心代碼:
# 返回基礎(chǔ)頁(yè)面 def happy(request): user_info = UserInfo() # 初始用戶名為匿名用戶 user_name = "匿名用戶" user_info.user_name = user_name # 利用時(shí)間產(chǎn)生臨時(shí)ID user_id = int(time.time()) user_info.user_id = user_id # 獲取用戶ip user_ip = wrappers.get_client_ip(request) user_info.user_ip = user_ip user_info.save() return render(request, 'chatroom/happy.html', locals()) # 保存聊天內(nèi)容 def save_chat_log(request): try: print("后端收到了ajax消息") chatinfo = ChatInfo() # 獲取前端傳過(guò)來(lái)的數(shù)據(jù) chat_content = wrappers.post(request, "chat_content") user_ip = wrappers.get_client_ip(request) user_name = wrappers.post(request, "user_name") user_id = wrappers.post(request, "user_id") # 將數(shù)據(jù)存入數(shù)據(jù)庫(kù) chatinfo.chat_content = chat_content chatinfo.user_ip = user_ip chatinfo.user_name = user_name chatinfo.user_id = user_id chatinfo.save() return JsonResponse({"ret":0}) except: return JsonResponse({"ret":"保存出現(xiàn)問(wèn)題"}) pass # 獲取最近的聊天信息 def get_near_log(request): try: # 獲取數(shù)據(jù)庫(kù)內(nèi)所有的信息 all_info = ChatInfo.objects.all() # 獲取數(shù)據(jù)庫(kù)內(nèi)最后一條消息的id id_max =ChatInfo.objects.aggregate(Max('id')) last_id = id_max["id__max"] # print("后臺(tái)數(shù)據(jù)庫(kù)內(nèi)最新的id為", last_id) # 獲取請(qǐng)求的id值 old_last_id = wrappers.post(request, "last_id") print(old_last_id,"<-<-") print(old_last_id, type(old_last_id),"-->") # print("后臺(tái)發(fā)送過(guò)來(lái)的id為",old_last_id) # 返回的信息字典,返回當(dāng)前時(shí)間(current_date),返回信息列表(id_info) # 如果第一次請(qǐng)求,則回復(fù)最后一條消息的id if int(old_last_id) == 0: user_ip = wrappers.get_client_ip(request) result_dict = dict() result_dict["last_id"] = last_id result_dict["info"] = [{"id":"-->", "mess":"歡迎"+user_ip+"來(lái)到聊天室!", "user_name":"系統(tǒng)消息:"}] result_dict["user_id"] = "" result_dict = json.dumps(result_dict,ensure_ascii=False) # print("第一次握手") return JsonResponse({"data":result_dict}) # 如果數(shù)據(jù)內(nèi)沒(méi)有消息更新 elif int(old_last_id) >= int(last_id): result_dict = dict() result_dict["last_id"] = last_id result_dict["info"] = [{last_id:"歡迎再次來(lái)到聊天室!"}] result_dict["user_id"] = "" result_dict = json.dumps(result_dict,ensure_ascii=False) # print("一次無(wú)更新的交互") return JsonResponse({"data":result_dict}) # 如果有消息更新 else: # print("有更新的回復(fù)") result_dict = dict() # 獲取新的消息對(duì)象集合 the_new_info =ChatInfo.objects.filter(id__gt=old_last_id) # 創(chuàng)建消息列表 mess_list = list() # 將最新的消息組成字典進(jìn)行返回 for info in the_new_info: # print(info) # print ("-->",info.chat_content, info.id) # 創(chuàng)建消息字典 mess_dic = dict() mess_dic["id"] = info.id mess_dic["mess"] = info.chat_content # 將消息所屬的用戶添加到消息列表 mess_dic["user_name"] = info.user_name mess_dic["user_id"] = info.user_id # 將消息字典添加到消息列表 mess_list.append(mess_dic) result_dict["last_id"] = last_id result_dict["info"] = mess_list # result_dict["info"] = [{"id":3, "mess":"hahah"}, {"id":4, "mess":"666"}] result_dict = json.dumps(result_dict,ensure_ascii=False) # print("--->>>", type(result_dict)) return JsonResponse({"data":result_dict}) except: return JsonResponse({"ret":"刷新出現(xiàn)問(wèn)題"}) pass
總結(jié)
以上所述是小編給大家介紹的Python使用django框架實(shí)現(xiàn)多人在線匿名聊天的小程序,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
- 基于django channel實(shí)現(xiàn)websocket的聊天室的方法示例
- Django Channel實(shí)時(shí)推送與聊天的示例代碼
- Django Channels 實(shí)現(xiàn)點(diǎn)對(duì)點(diǎn)實(shí)時(shí)聊天和消息推送功能
- vue+django實(shí)現(xiàn)一對(duì)一聊天功能的實(shí)例代碼
- django使用channels實(shí)現(xiàn)通信的示例
- 淺談django channels 路由誤導(dǎo)
- 詳解Django-channels 實(shí)現(xiàn)WebSocket實(shí)例
- Django使用Channels實(shí)現(xiàn)WebSocket的方法
- django使用channels2.x實(shí)現(xiàn)實(shí)時(shí)通訊
- Django使用channels + websocket打造在線聊天室
相關(guān)文章
淺談tf.train.Saver()與tf.train.import_meta_graph的要點(diǎn)
這篇文章主要介紹了淺談tf.train.Saver() 與tf.train.import_meta_graph的要點(diǎn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05Python使用asyncio包處理并發(fā)的實(shí)現(xiàn)代碼
這篇文章主要介紹了Python使用asyncio包處理并發(fā),asyncio包使用事件循環(huán)驅(qū)動(dòng)的協(xié)程實(shí)現(xiàn)并發(fā),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì)對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-12-12Django在pycharm下修改默認(rèn)啟動(dòng)端口的方法
今天小編就為大家分享一篇Django在pycharm下修改默認(rèn)啟動(dòng)端口的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07Python實(shí)現(xiàn)的邏輯回歸算法示例【附測(cè)試csv文件下載】
這篇文章主要介紹了Python實(shí)現(xiàn)的邏輯回歸算法,結(jié)合具體實(shí)例形式分析了Python邏輯回歸算法相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-12-12python回調(diào)函數(shù)用法實(shí)例分析
這篇文章主要介紹了python回調(diào)函數(shù)用法,較為詳細(xì)的分析了常用的調(diào)用方式,并實(shí)例介紹了Python回調(diào)函數(shù)的使用技巧,需要的朋友可以參考下2015-05-05用Pytorch實(shí)現(xiàn)線性回歸模型的步驟
線性關(guān)系是一種非常簡(jiǎn)單的變量之間的關(guān)系,因變量和自變量在線性關(guān)系的情況下,可以使用線性回歸算法對(duì)一個(gè)或多個(gè)因變量和自變量間的線性關(guān)系進(jìn)行建模,本文主要介紹了如何利用Pytorch實(shí)現(xiàn)線性模型,需要的朋友可以參考下2024-01-01python基于三階貝塞爾曲線的數(shù)據(jù)平滑算法
這篇文章主要介紹了python基于三階貝塞爾曲線的數(shù)據(jù)平滑算法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12python進(jìn)度條庫(kù)tqdm使用記錄(特點(diǎn)和用法)
tqdm是一個(gè)Python庫(kù),用于在命令行界面中創(chuàng)建美觀的進(jìn)度條,以跟蹤代碼中循環(huán)、迭代和任務(wù)的執(zhí)行進(jìn)度,本文給大家介紹python進(jìn)度條庫(kù)tqdm使用記錄,感興趣的朋友跟隨小編一起看看吧2023-10-10