[Flask] Overriding get_id()
Why Overriding get_id() Matters in Flask-Login with MongoDB
When using MongoDB for user database, the user
_id is typically a bson.ObjectId, which isn’t JSON-serializable by default. This can cause unexpected errors in the Flask session handling. How get_id() Is Called
When using Flask-Login, a
UserMixin class is often used that provides default implementations for methods like get_id(). Even if this method is not called directly, Flask-Login does. For example:-
When logging in a user via
login_user(user), Flask-Login stores that user’s ID in the session. -
When Flask-Login reconstructs the user on subsequent requests, it looks up the user by the stored ID.
If that ID isn’t a simple string, it might cause a “TypeError: Object of type ObjectId is not JSON serializable”.
Overriding get_id()
To fix this, explicitly convert the MongoDB _id to a string:
from flask_login import UserMixin
class User(UserMixin): def __init__(self, user_id, user_email, game_list): self.user_id = user_id self.user_email = user_email self.game_list = game_list
# Override get_id() to return a string def get_id(self): return str(self.user_id)
Why It Works
Flask-Login stores the value returned by get_id() in the session. By returning a string, it is ensured that there’s no serialization error—Flask can safely handle it, and the “Object of type ObjectId is not JSON serializable” error is avoided.
Comments
Post a Comment