简体   繁体   English

使用 flask-socketio 添加到数据库

[英]Add to Database using flask-socketio

I want to use flask_socketio to add realtime messaging function to my web.我想使用 flask_socketio 向我的网络添加实时消息传递功能。 My website has a function in which messages are added to the messages table in my flask-sqlalchemy db.我的网站有一个功能,可以将消息添加到我的 flask-sqlalchemy 数据库中的消息表中。 Now Im unable to understand how will I add a message to the database while at the same time posting it to the client server so it can instantly ne viewed, in easy words what flask-socketio is used for(instant update).The function to add messages is:现在我无法理解如何将消息添加到数据库,同时将其发布到客户端服务器,以便可以立即查看它,简单来说,flask-socketio 用于(即时更新)。函数添加消息是:

@app.route('/<int:team_id>/<int:channel_id>/<string:channel_name>' , methods=["GET","POST"])
def channel(team_id,channel_id, channel_name):
*Irrelevant code*
 form = MessageForm()
 if form.validate_on_submit():
    message = Messages(msg_cntnt=form.msg_cntnt.data,msg_file
    =form.picture.data, sender_id=current_user.id)
            message.parent_channel = _channel_name
    db.session.add(message)
    db.session.commit()    
messages = Messages.query.filter_by(parent_channel=_channel_name).all()
return render_template('team.html', _channel=_channel, team=team, channels=channels,
team_members_count=team_members_count, form=form, messages=messages)

I have tried a few ways of using flask socketio with it none worked.我尝试了几种使用flask socketio的方法,但都没有奏效。 I also tried changing version of flask_socketio from 5.2.0 to 2 and then 4 but it didn't work.我还尝试将 flask_socketio 的版本从 5.2.0 更改为 2,然后更改为 4,但它没有用。 How can I achieve this?我怎样才能做到这一点? How can I add flask-socketio to it.我怎样才能将flask-socketio添加到它。 NOTE: In my team.html I have done:注意:在我的 team.html 中,我已经完成了:

You could prioritize the realtime functionality first and saved it afterwards like this您可以先优先考虑实时功能,然后像这样保存它

def save_message(msg):
  groupid = group.query.filter(group.groupid == msg["roomid"]).first()
  save = message(msg["sender"],msg["content"])
  db.session.add(save)
  groupid.message.append(save)
  db.session.commit()
  
  

@socketio.on("send_message")
def send_message(message):
  print(message)
  message["sender"] = current_user.username
  emit('add_element', message, to = message["roomid"], broadcast = True)
  save_message(message)

When "send_message" event is triggered then act like a normal emit message function, but after everything is done (transmission of real time message) then call a function that saves the message当“send_message”事件被触发时,就像一个正常的发送消息函数一样,但是在一切都完成之后(实时消息的传输)然后调用一个保存消息的函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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