Python使用django框架實現(xiàn)多人在線匿名聊天的小程序
最近看到好多設計類網(wǎng)站,都提供了多人在線匿名聊天的小功能,感覺很有意思,于是基于python的django框架自己寫了一個,支持手動實時更名,最下方提供了完整的源碼.
在線聊天地址(無需登錄,開一個窗口,代表一個用戶):
http://zhaozhaoli.vicp.io/chatroom/happy/
移動端聊天效果圖:
網(wǎng)頁版聊天效果圖:
實現(xiàn)思路:
發(fā)送的消息通過ajax先寫入數(shù)據(jù)庫,通過ajax的循環(huán)請求,將寫入數(shù)據(jù)庫的消息顯示到前端界面.
前端核心代碼:
<script> $(function () { $("#send").click(function () { var input_info = $("#input_info").val(); if (input_info.length < 1) { alert("請輸入字符后發(fā)送"); return; } else if (input_info.length > 200) { alert("每次發(fā)送不可以超出200個字符哈~"); 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; } //獲取后臺傳過來的id值,并將值存儲到全局變量中 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)聽鍵盤點擊 $(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("昵稱長度應為1-10,請重新輸入"); $("#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>
后端核心代碼:
# 返回基礎頁面 def happy(request): user_info = UserInfo() # 初始用戶名為匿名用戶 user_name = "匿名用戶" user_info.user_name = user_name # 利用時間產(chǎn)生臨時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() # 獲取前端傳過來的數(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ù)庫 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)問題"}) pass # 獲取最近的聊天信息 def get_near_log(request): try: # 獲取數(shù)據(jù)庫內(nèi)所有的信息 all_info = ChatInfo.objects.all() # 獲取數(shù)據(jù)庫內(nèi)最后一條消息的id id_max =ChatInfo.objects.aggregate(Max('id')) last_id = id_max["id__max"] # print("后臺數(shù)據(jù)庫內(nèi)最新的id為", last_id) # 獲取請求的id值 old_last_id = wrappers.post(request, "last_id") print(old_last_id,"<-<-") print(old_last_id, type(old_last_id),"-->") # print("后臺發(fā)送過來的id為",old_last_id) # 返回的信息字典,返回當前時間(current_date),返回信息列表(id_info) # 如果第一次請求,則回復最后一條消息的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+"來到聊天室!", "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)沒有消息更新 elif int(old_last_id) >= int(last_id): result_dict = dict() result_dict["last_id"] = last_id result_dict["info"] = [{last_id:"歡迎再次來到聊天室!"}] result_dict["user_id"] = "" result_dict = json.dumps(result_dict,ensure_ascii=False) # print("一次無更新的交互") return JsonResponse({"data":result_dict}) # 如果有消息更新 else: # print("有更新的回復") result_dict = dict() # 獲取新的消息對象集合 the_new_info =ChatInfo.objects.filter(id__gt=old_last_id) # 創(chuàng)建消息列表 mess_list = list() # 將最新的消息組成字典進行返回 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)問題"}) pass
總結(jié)
以上所述是小編給大家介紹的Python使用django框架實現(xiàn)多人在線匿名聊天的小程序,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- 基于django channel實現(xiàn)websocket的聊天室的方法示例
- Django Channel實時推送與聊天的示例代碼
- Django Channels 實現(xiàn)點對點實時聊天和消息推送功能
- vue+django實現(xiàn)一對一聊天功能的實例代碼
- django使用channels實現(xiàn)通信的示例
- 淺談django channels 路由誤導
- 詳解Django-channels 實現(xiàn)WebSocket實例
- Django使用Channels實現(xiàn)WebSocket的方法
- django使用channels2.x實現(xiàn)實時通訊
- Django使用channels + websocket打造在線聊天室
相關(guān)文章
淺談tf.train.Saver()與tf.train.import_meta_graph的要點
這篇文章主要介紹了淺談tf.train.Saver() 與tf.train.import_meta_graph的要點,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05Python使用asyncio包處理并發(fā)的實現(xiàn)代碼
這篇文章主要介紹了Python使用asyncio包處理并發(fā),asyncio包使用事件循環(huán)驅(qū)動的協(xié)程實現(xiàn)并發(fā),本文通過實例代碼給大家介紹的非常詳細對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-12-12Python實現(xiàn)的邏輯回歸算法示例【附測試csv文件下載】
這篇文章主要介紹了Python實現(xiàn)的邏輯回歸算法,結(jié)合具體實例形式分析了Python邏輯回歸算法相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2018-12-12python基于三階貝塞爾曲線的數(shù)據(jù)平滑算法
這篇文章主要介紹了python基于三階貝塞爾曲線的數(shù)據(jù)平滑算法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-12-12