简体   繁体   中英

How to automatically give a unique id to each message in flask-socketio?

 let user_input = $( 'textarea.message' ).val() let v = user_input.trim() if (v) { let user_name = "You" let today = new Date(); let date = today.getDate()+'-'+(today.getMonth()+1)+'-'+today.getFullYear() let time = today.getHours() + ":" + today.getMinutes() socket.emit( 'my event', { msg_id: id, // I want an id assigned every time a message is written here user_name: user_name, message: user_input, time_now: String(date+","+time) } ) $( 'textarea.message' ).val( '' ).focus()

**Does Flask-socketio provide an easy way to do this or should i do it with Javascript myself? ** What is the best way to do this with Javascript?

I assume You can use built in python uuid library for generating unique id

import uuid
unique_id = uuid.uuid4()
print(unique_id)  // UUID('8441edfd-297c-4bb7-8803-aee9f5675e36')

 let user_input = $( 'textarea.message' ).val() let v = user_input.trim() if (v) { let user_name = "You" let today = new Date(); let date = today.getDate()+'-'+(today.getMonth()+1)+'-'+today.getFullYear() let time = today.getHours() + ":" + today.getMinutes() if (typeof id == 'undefined') { id = 0 } function plus() { id += 1; return id } socket.emit( 'my event', { msg_id: plus(), // Each new message id will increase by 1 digit user_name: user_name, message: user_input, time_now: String(date+","+time) } ) $( 'textarea.message' ).val( '' ).focus()

I did this the simple my way.I will restore the chat history every time the user logs on to the site and and I'll take the last id in the chat history and continue with it.So, I have defined a unique and simple id for each message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM