Python uses the django framework to implement a small program for online anonymous chat among multiple users, pythondjango

Source: Internet
Author: User
Tags wrappers

Python uses the django framework to implement a small program for online anonymous chat among multiple users, pythondjango

Recently, many design websites have provided small online and anonymous chat functions for multiple users. This is very interesting, so I wrote a new one based on the python django framework, which supports manual real-time renaming, the complete source code is provided at the bottom.

Online Chat address (no need to log on, open a window to represent a user ):

Http://zhaozhaoli.vicp.io/chatroom/happy/

Mobile chat:

Web chat:

Implementation ideas:

The sent messages are written to the database through ajax, and the messages written to the database are displayed on the front-end interface through ajax loop requests.

Core front-end code:

<Script> $ (function () {$ ("# send "). click (function () {var input_info = $ ("# input_info "). val (); if (input_info.length <1) {alert ("Enter the character and send it"); return;} else if (input_info.length> 200) {alert ("each sending cannot exceed 200 characters ~ "); Return;} else {// obtain the csrftoken value 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': '2017. 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 get the latest data $. 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;} // obtain the id value passed in the background and store the value in the global variable last_id = JSON. parse (data. data ). last_id; // read the content and print 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 () {// listen to the keyboard and click $ (document ). keyup (function (event) {if (event. keyCode = 13) {$ ("# send "). click () ;}}) </script> <script >$ (function () {$ ("# change_name "). click (function () {// obtain the new name var new_name = String ($ ("# new_name "). val (); // check whether the new name is valid // if (new_name.length <11 & new_name.length> 0) {console. log (new_name); $ ("# user_name "). text (new_name); $ ("# new_name "). val ("")} else {alert ("the length of the nickname should be 1-10. Please enter"); $ ("# new_name "). val ("") }}) </script> <div id = "main_form"> <div class = "my_nike_name"> my nickname: <span id = "user_name" >{{ user_name }}</span> <button id = "change_name"> rename </button> <input type = "text" id = "new_name"> </span> </div> <div id = "show_info"> <div id = "content"> </div> <br> <div class = "my_nike_name"> message </div> <input type = "text" id = "input_info"> <button id = "send"> send message </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>

Core back-end code:

# Return basic page def happy (request): user_info = UserInfo () # The initial user name is anonymous user user_name = "anonymous user" user_info.user_name = user_name # generate a temporary ID user_id = int (time. time () user_info.user_id = user_id # Get user ip user_ip = wrappers. get_client_ip (request) user_info.user_ip = user_ip user_info.save () return render (request, 'chatroom/happy.html ', locals () # Save the chat content def save_chat_log (request): try: print ("the backend receives the ajax message") chati Nfo = ChatInfo () # obtain the data uploaded by the front-end 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") # store data in the database 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}) ex Cept: return JsonResponse ({"ret": "An error occurred while saving"}) pass # obtain the latest chat information def get_near_log (request): try: # obtain all information in the database all_info = ChatInfo. objects. all () # obtain the id id_max = ChatInfo of the last message in the database. objects. aggregate (Max ('id') last_id = id_max ["id _ max"] # print ("the latest id in the background database is", last_id) # obtain the Request id value old_last_id = wrappers. post (request, "last_id") print (old_last_id, "<-") print (old_last_id, type (old_last_id), "-->") # print ("The id sent from the background is", old_last_id) # returns the information dictionary, returns the current time (current_date), and returns the Information List (id_info) # If the first request is made, the 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 ": "Welcome" + user_ip + "to the chat room! "," User_name ":" system message: "}] result_dict [" user_id "] =" "result_dict = json. dumps (result_dict, ensure_ascii = False) # print ("first handshake") return JsonResponse ({"data": result_dict}) # if there is no message in the data, update elif int (old_last_id)> = int (last_id): result_dict = dict () result_dict ["last_id"] = last_id result_dict ["info"] = [{last_id: "Welcome to the chat room again! "}] Result_dict [" user_id "] =" "result_dict = json. dumps (result_dict, ensure_ascii = False) # print ("one interaction without updating") return JsonResponse ({"data": result_dict}) # If a message is sent, update else: # print ("updated reply") result_dict = dict () # Get the new message object set the_new_info = ChatInfo. objects. filter (id _ gt = old_last_id) # create a message list mess_list = list () # combine the latest messages into a dictionary and return for info in the_new_info: # print (info) # print ("-->", info. chat_content, info. id) # create a message dictionary mess_dic = dict () mess_dic ["id"] = info. id mess_dic ["mess"] = info. chat_content # Add the user to which the message belongs to the mess_dic ["user_name"] = info. user_name mess_dic ["user_id"] = info. user_id # Add the message dictionary to the message list 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}) failed t: return JsonResponse ({"ret": "refreshing failed"}) pass

Summary

The above is a small program that uses the django framework to implement anonymous online chat for many people. I hope it will be helpful to you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.