ajax_handler.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import json
  2. from . import libdata
  3. from . import util
  4. source_filename = "ajax_handler"
  5. #模擬AJAX。前端 -> 後端
  6. def parse_ajax_msg(msg):
  7. """parse message from browser
  8. Parameters
  9. ----------
  10. msg : JSON
  11. requset message
  12. Returns
  13. -------
  14. JSON
  15. parsed result
  16. """
  17. try:
  18. msg_dict = json.loads(msg)
  19. except Exception as err:
  20. util.console.error(err, f"{source_filename}.parse_ajax_msg")
  21. util.console.log("Error load Json!")
  22. return
  23. # in case client side run JSON.stringify twice
  24. if (type(msg_dict) == str):
  25. msg_dict = json.loads(msg_dict)
  26. if "action" not in msg_dict.keys():
  27. util.console.error("Can not find action from js request", f"{source_filename}.parse_ajax_msg")
  28. return
  29. action = msg_dict["action"]
  30. if not action:
  31. util.console.error("Action from js request is None", f"{source_filename}.parse_ajax_msg")
  32. return
  33. if action not in libdata.ajax_actions:
  34. util.console.error("Unknow action: " + action, f"{source_filename}.parse_ajax_msg")
  35. return
  36. return msg_dict
  37. #模擬AJAX。後端 -> 前端
  38. def build_py_msg(action:str, content:dict):
  39. """sent message to browser
  40. Parameters
  41. ----------
  42. action : str
  43. requset header
  44. content : dict
  45. requset content
  46. Returns
  47. -------
  48. JSON
  49. message to sent
  50. """
  51. util.console.start("build_py_msg")
  52. if not content:
  53. util.console.error("Content is None", f"{source_filename}.build_py_msg")
  54. return
  55. if not action:
  56. util.console.error("Action is None", f"{source_filename}.build_py_msg")
  57. return
  58. if action not in libdata.py_actions:
  59. util.console.error("Unknow action: " + action, f"{source_filename}.build_py_msg")
  60. return
  61. msg = {
  62. "action" : action,
  63. "content": content
  64. }
  65. util.console.end("build_py_msg")
  66. return json.dumps(msg)