sxweb.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import traceback
  2. import numpy as np
  3. from decorator import decorator
  4. from fastapi.responses import JSONResponse
  5. def json_compatible(data):
  6. if isinstance(data,dict):
  7. return {k:json_compatible(v) for k,v in data.items()}
  8. if isinstance(data,bytes):
  9. return str(data)
  10. if isinstance(data,np.ndarray):
  11. return data.tolist()
  12. return data
  13. def web_try(exception_ret=None):
  14. @decorator
  15. def f(func, *args, **kwargs):
  16. error_code = "000"
  17. ret = None
  18. msg = ''
  19. try:
  20. ret = func(*args, **kwargs)
  21. except Exception as e:
  22. msg = traceback.format_exc()
  23. if len(e.args) > 0 and isinstance(e.args[0], int):
  24. error_code = e.args[0]
  25. else:
  26. error_code = "101"
  27. print('--------------------------------')
  28. print ('Get Exception in web try :( \n{}\n'.format(msg))
  29. print('--------------------------------')
  30. if callable(exception_ret):
  31. ret = exception_ret()
  32. else:
  33. ret = exception_ret
  34. finally:
  35. if ret is not None and isinstance(ret, JSONResponse):
  36. return ret
  37. return json_compatible({"status": error_code,
  38. "result": ret,
  39. "msg": msg.split('\n')[-2] if msg is not '' else msg})
  40. return f