High schooler High schooler - 1 year ago 277
Python Question

Flask-Login + Flask-Sockets = Chaos

I have installed Flask-Login and Flask-Sockets. Both of them work fine HOWEVER when I try to get the current user (using g.user), I get an

AttributeError: '_AppCtxGlobals' object has no attribute 'user'

def echo_socket(ws):
with app.app_context():
user = current_user #This causes problems, just like basically anything else that uses something that is not provided in this function
while True:
message = ws.receive()

I am still new with Flask, any help would be super appreciated.

Answer Source

The problem is that you are treating your socket functions as if they were regular requests, which they are not.

In a regular (i.e. non-socket) situation the client sends requests to the server. Each request contains a cookie that was set at login time by Flask-Login. This cookie contains the user that is logged in. Flask-Login has a before_request handler that reads this cookie, loads the user and then exposes it through current_user, so that by the time your function runs you have access to this information.

Socket connections are nothing like the above. For a socket connection the client opens a socket to a route and that establishes a permanent connection with the server. The concept of a request does not exist here, it's just two machines sending and receiving data using their own protocol. Because there are no HTTP requests there is also no cookies, no before_request handlers, no application and request contexts pushed and no current_user from Flask-Login. The socket routes really function outside of the Flask application.

If you need to know the user you will need to have the client send credentials through the socket interface, and you will need to authenticate those credentials in your socket route on your own, since Flask-Login cannot work in the socket environment due to the lack of requests, cookies, etc. A significant difference between sockets and regular routes is that the socket connection is permanent, so you only need to authenticate the user when the connection is established.

I hope this helps. Sorry I don't have a quick and easy solution for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download