Summary
Save.post() in web/app.py (lines 149-158) retrieves the entire Messages array from MongoDB into Python memory, appends the new message locally, then writes the full array back with $set. This is an unnecessary round-trip and will degrade as the messages list grows. MongoDB's $push operator appends atomically in a single update command.
Background
The current pattern introduces a TOCTOU race: two concurrent saves for the same user can overwrite each other's messages. Using $push eliminates both the read round-trip and the race condition, which is the idiomatic MongoDB approach.
Affected Areas
web/app.py — Save.post(), lines 149-158
get_user_messages() helper — still needed for Retrieve, but no longer called from Save
Recommended Fix
class Save(Resource):
@requires_auth
def post(self):
data = request.get_json(silent=True, force=True)
if not data:
return {"status": 400, "msg": "Request body must be valid JSON"}, 400
message = data.get("message")
if not message:
return {"status": 400, "msg": "message is required"}, 400
users.update_one(
{"Username": request.username},
{"$push": {"Messages": message}}
)
return {"status": 200, "msg": "Message has been saved successfully"}, 200
Acceptance Criteria
Complexity Estimate
XS — three lines replaced, no new dependencies.
Priority
Medium — correctness (race condition) justifies fixing even in a tutorial; also teaches idiomatic MongoDB.
Auto-identified by workspace issue-logger
Category: code optimisation / performance
Complexity: XS
Repository: DewaldOosthuizen/python_rest_tutorial
Summary
Save.post()inweb/app.py(lines 149-158) retrieves the entireMessagesarray from MongoDB into Python memory, appends the new message locally, then writes the full array back with$set. This is an unnecessary round-trip and will degrade as the messages list grows. MongoDB's$pushoperator appends atomically in a single update command.Background
The current pattern introduces a TOCTOU race: two concurrent saves for the same user can overwrite each other's messages. Using
$pusheliminates both the read round-trip and the race condition, which is the idiomatic MongoDB approach.Affected Areas
web/app.py—Save.post(), lines 149-158get_user_messages()helper — still needed forRetrieve, but no longer called fromSaveRecommended Fix
Acceptance Criteria
Save.post()uses a singleupdate_onewith$push— no priorget_user_messagescallget_user_messageshelper retained for use byRetrieveComplexity Estimate
XS — three lines replaced, no new dependencies.
Priority
Medium — correctness (race condition) justifies fixing even in a tutorial; also teaches idiomatic MongoDB.
Auto-identified by workspace issue-logger
Category: code optimisation / performance
Complexity: XS
Repository: DewaldOosthuizen/python_rest_tutorial