refactor: Use JSON for session data (#25207)

JSON is proper format compared to using safe_eval which is a hack to convert
string repr of dict object back into python object.
This commit is contained in:
Ankush Menat 2024-03-04 12:17:48 +05:30 committed by GitHub
parent b1a8bc9312
commit 7a854efc03
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 39 additions and 3 deletions

View file

@ -234,3 +234,4 @@ frappe.core.doctype.data_import.patches.remove_stale_docfields_from_legacy_versi
frappe.patches.v15_0.validate_newsletter_recipients
frappe.patches.v15_0.sanitize_workspace_titles
frappe.patches.v15_0.migrate_role_profile_to_table_multi_select
frappe.patches.v15_0.migrate_session_data

View file

@ -0,0 +1,24 @@
import frappe
from frappe.utils import update_progress_bar
def execute():
frappe.db.auto_commit_on_many_writes = True
Sessions = frappe.qb.DocType("Sessions")
current_sessions = (frappe.qb.from_(Sessions).select(Sessions.sid, Sessions.sessiondata)).run(
as_dict=True
)
for i, session in enumerate(current_sessions):
try:
new_data = frappe.as_json(frappe.safe_eval(session.sessiondata))
except Exception:
# Rerunning patch or already converted.
continue
(
frappe.qb.update(Sessions).where(Sessions.sid == session.sid).set(Sessions.sessiondata, new_data)
).run()
update_progress_bar("Patching sessions", i, len(current_sessions))

View file

@ -258,7 +258,15 @@ class Session:
(
frappe.qb.into(Sessions)
.columns(Sessions.sessiondata, Sessions.user, Sessions.lastupdate, Sessions.sid, Sessions.status)
.insert((str(self.data["data"]), self.data["user"], now, self.data["sid"], "Active"))
.insert(
(
frappe.as_json(self.data["data"], indent=None, separators=(",", ":")),
self.data["user"],
now,
self.data["sid"],
"Active",
)
)
).run()
frappe.cache.hset("session", self.data.sid, self.data)
@ -332,7 +340,7 @@ class Session:
).run()
if record:
data = frappe._dict(frappe.safe_eval(record and record[0][1] or "{}"))
data = frappe.parse_json(record[0][1] or "{}")
data.user = record[0][0]
else:
self._delete_session()
@ -371,7 +379,10 @@ class Session:
(
frappe.qb.update(Sessions)
.where(Sessions.sid == self.data["sid"])
.set(Sessions.sessiondata, str(self.data["data"]))
.set(
Sessions.sessiondata,
frappe.as_json(self.data["data"], indent=None, separators=(",", ":")),
)
.set(Sessions.lastupdate, now)
).run()