欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2017年11月29日 14:35:53   作者:_昭昭_  
很多網(wǎng)站都提供了在線匿名聊天的小功能,下面小編基于python的django框架實現(xiàn)一個多人在線匿名聊天的小程序,具體實現(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)站的支持!

相關(guān)文章

  • 淺談tf.train.Saver()與tf.train.import_meta_graph的要點

    淺談tf.train.Saver()與tf.train.import_meta_graph的要點

    這篇文章主要介紹了淺談tf.train.Saver() 與tf.train.import_meta_graph的要點,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • Python使用asyncio包處理并發(fā)的實現(xiàn)代碼

    Python使用asyncio包處理并發(fā)的實現(xiàn)代碼

    這篇文章主要介紹了Python使用asyncio包處理并發(fā),asyncio包使用事件循環(huán)驅(qū)動的協(xié)程實現(xiàn)并發(fā),本文通過實例代碼給大家介紹的非常詳細對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-12-12
  • Django在pycharm下修改默認啟動端口的方法

    Django在pycharm下修改默認啟動端口的方法

    今天小編就為大家分享一篇Django在pycharm下修改默認啟動端口的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • 對pandas的層次索引與取值的新方法詳解

    對pandas的層次索引與取值的新方法詳解

    今天小編就為大家分享一篇對pandas的層次索引與取值的新方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-11-11
  • Python實現(xiàn)的邏輯回歸算法示例【附測試csv文件下載】

    Python實現(xiàn)的邏輯回歸算法示例【附測試csv文件下載】

    這篇文章主要介紹了Python實現(xiàn)的邏輯回歸算法,結(jié)合具體實例形式分析了Python邏輯回歸算法相關(guān)實現(xiàn)技巧,需要的朋友可以參考下
    2018-12-12
  • python回調(diào)函數(shù)用法實例分析

    python回調(diào)函數(shù)用法實例分析

    這篇文章主要介紹了python回調(diào)函數(shù)用法,較為詳細的分析了常用的調(diào)用方式,并實例介紹了Python回調(diào)函數(shù)的使用技巧,需要的朋友可以參考下
    2015-05-05
  • Python中一般處理中文的幾種方法

    Python中一般處理中文的幾種方法

    今天小編就為大家分享一篇關(guān)于Python中一般處理中文的幾種方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • 用Pytorch實現(xiàn)線性回歸模型的步驟

    用Pytorch實現(xiàn)線性回歸模型的步驟

    線性關(guān)系是一種非常簡單的變量之間的關(guān)系,因變量和自變量在線性關(guān)系的情況下,可以使用線性回歸算法對一個或多個因變量和自變量間的線性關(guān)系進行建模,本文主要介紹了如何利用Pytorch實現(xiàn)線性模型,需要的朋友可以參考下
    2024-01-01
  • python基于三階貝塞爾曲線的數(shù)據(jù)平滑算法

    python基于三階貝塞爾曲線的數(shù)據(jù)平滑算法

    這篇文章主要介紹了python基于三階貝塞爾曲線的數(shù)據(jù)平滑算法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-12-12
  • python進度條庫tqdm使用記錄(特點和用法)

    python進度條庫tqdm使用記錄(特點和用法)

    tqdm是一個Python庫,用于在命令行界面中創(chuàng)建美觀的進度條,以跟蹤代碼中循環(huán)、迭代和任務的執(zhí)行進度,本文給大家介紹python進度條庫tqdm使用記錄,感興趣的朋友跟隨小編一起看看吧
    2023-10-10

最新評論