So I am working on a chat app. When a new user registers, others users on a should get notified about it without refreshing.
So I made a form where whenever users registers , I send it's username using sockets. where I check if the user is in database and then emit users information to another page.
$("#submit").click(function(){
socket.emit("register",$(".username").val())
})
The problem is that it takes time for data to insert into database and till then the emit event is executed and my check whether the new user is in database returns none always.
@socketio.on('register')
def test_connect(data):
user = Detail.query.filter_by(username=data).first()
print(user) # this always return none and emit event doesn't take place
if user:
emit("regis",user.username,broadcast=True ,include_self=False)
here is the relevant part of register function where I validate form and insert data.
form = RegistrationForm()
if request.method=="POST" and form.validate_on_submit():
user = Detail(username=form.username.data,email=form.email.data,password=form.password.data)
db.session.add(user)
db.session.commit()
return redirect("/signin")
Is there a way I can ensure that the emit event occurs only when if request.method=="POST" and form.validate_on_submit():
returns true so that the data is inserted into database and after that emit event takes place.
I have tried emitting in the route using this question but it doesn't seem to work , the function socket.io doesn't execute.
Any suggestions will we strongly appreciated.
@miguel Thanks for replying , yes it is asynchronous. It is basic login forms and when user registers , the page redirects to login page and user disconnects.
I don't think that callback will work as the page redirects to other page.
However , I found a solution to emit event in a route.
I used this after database commit in register
route.
socketio.on_event('register', test_connect(user.username),namespace="/")
then I defined the test_connect function.
def test_connect(data):
emit("regis",data,broadcast=True ,namespace="/")
This worked for me , but as mentioned in docs.
For cases when a decorator syntax isn’t convenient, the on_event method can be used:
def my_function_handler(data): pass socketio.on_event('my event', my_function_handler, namespace='/test')
when I only use socketio.on_event('register', test_connect ,namespace="/")
, the emit event test_connect function is not executed.
So I need to call the function and give a parameter to make it work. I don't know why it is not working , there are no errors.
However my code is working prefectly.