最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python使用django框架實現(xiàn)多人在線匿名聊天的小程序

 更新時間:2017年11月29日 14:35:53   作者:_昭昭_  
很多網(wǎng)站都提供了在線匿名聊天的小功能,下面小編基于python的django框架實現(xiàn)一個多人在線匿名聊天的小程序,具體實現(xiàn)代碼大家參考下本文

最近看到好多設(shè)計類網(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("昵稱長度應(yīng)為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>

后端核心代碼:

# 返回基礎(chǔ)頁面
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)
  # 如果第一次請求,則回復(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+"來到聊天室!", "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("有更新的回復(fù)")
   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)多人在線匿名聊天的小程序,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

  • Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)實現(xiàn)對不原生支持比較操作的對象排序算法示例

    Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)實現(xiàn)對不原生支持比較操作的對象排序算法示例

    這篇文章主要介紹了Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)實現(xiàn)對不原生支持比較操作的對象排序算法,結(jié)合實例形式分析了Python針對類實例進行排序相關(guān)操作技巧,需要的朋友可以參考下
    2018-03-03
  • 關(guān)于python time庫整理匯總

    關(guān)于python time庫整理匯總

    這篇文章主要給大家分享的是關(guān)于python time庫的整理,下面文章會介Time庫的作用,Time庫的使用及案列介紹,感興趣的小伙伴請和小拜年一起來閱讀下文吧
    2021-09-09
  • python讀寫LMDB文件的方法

    python讀寫LMDB文件的方法

    這篇文章主要為大家詳細介紹了python讀寫LMDB文件的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • python用opencv將標注提取畫框到對應(yīng)的圖像中

    python用opencv將標注提取畫框到對應(yīng)的圖像中

    這篇文章主要介紹了python用opencv將標注提取畫框到對應(yīng)的圖像中,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-08-08
  • python批量修改文件夾及其子文件夾下的文件內(nèi)容

    python批量修改文件夾及其子文件夾下的文件內(nèi)容

    這篇文章主要為大家詳細介紹了python批量修改文件夾及其子文件夾下的文件內(nèi)容,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-03-03
  • Python安裝pycurl失敗的解決方法

    Python安裝pycurl失敗的解決方法

    今天小編就為大家分享一篇Python安裝pycurl失敗的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-10-10
  • Python selenium的基本使用方法分析

    Python selenium的基本使用方法分析

    這篇文章主要介紹了Python selenium的基本使用方法,結(jié)合實例形式分析了Python使用selenium模塊進行web自動化測試的基本模塊導(dǎo)入、操作技巧與相關(guān)注意事項,需要的朋友可以參考下
    2019-12-12
  • Python logging模塊用法示例

    Python logging模塊用法示例

    這篇文章主要介紹了Python logging模塊用法,結(jié)合實例形式分析了Python logging模塊相關(guān)配置、函數(shù)、組件等操作方法與注意事項,需要的朋友可以參考下
    2018-08-08
  • Python識別快遞條形碼及Tesseract-OCR使用詳解

    Python識別快遞條形碼及Tesseract-OCR使用詳解

    這篇文章主要介紹了Python識別快遞條形碼及Tesseract-OCR使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-07-07
  • 詳解Python IO編程

    詳解Python IO編程

    這篇文章主要介紹了Python IO編程的相關(guān)資料,文中講解非常細致,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下
    2020-07-07

最新評論

松潘县| 郑州市| 通州区| 石屏县| 绵竹市| 榕江县| 子洲县| 白沙| 遂川县| 虹口区| 开原市| 大洼县| 富锦市| 平山县| 汾西县| 应用必备| 金溪县| 句容市| 沾化县| 鹤岗市| 都兰县| 乾安县| 铁岭市| 八宿县| 萍乡市| 宝应县| 德保县| 武乡县| 乐昌市| 广西| 麟游县| 肥城市| 海淀区| 绥芬河市| 和硕县| 烟台市| 万盛区| 邢台市| 固阳县| 肥东县| 广汉市|