common_api.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # File : common_api.py
  4. # Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
  5. # Author's Blog: https://blog.csdn.net/qq_32394351
  6. # Date : 2023/3/22
  7. from utils import parser
  8. from utils.env import get_env
  9. from base.R import R
  10. from flask import request,redirect
  11. from utils.log import logger
  12. def js_render(name):
  13. if not name or not name.split('.')[-1] in ['js','txt','py','json']:
  14. return R.error(f'非法猥亵,未指定文件名。必须包含js|txt|json|py')
  15. try:
  16. env = get_env()
  17. # print(env)
  18. if env.get('js_proxy'):
  19. js_proxy = env['js_proxy']
  20. burl = request.base_url
  21. if '=>' in js_proxy:
  22. oldsrc = js_proxy.split('=>')[0]
  23. if oldsrc in burl:
  24. newsrc = js_proxy.split('=>')[1]
  25. # print(f'js1源代理已启用,全局替换{oldsrc}为{newsrc}')
  26. rurl = burl.replace(oldsrc, newsrc)
  27. if burl != rurl:
  28. jscode = parser.getJs(name, 'js')
  29. # rjscode = render_template_string(jscode, env=env)
  30. rjscode = jscode
  31. for k in env:
  32. # print(f'${k}', f'{env[k]}')
  33. if f'${k}' in rjscode:
  34. rjscode = rjscode.replace(f'${k}', f'{env[k]}')
  35. # rjscode = render_template_string(jscode, **env)
  36. if rjscode.strip() == jscode.strip(): # 无需渲染才代理
  37. return redirect(rurl)
  38. else:
  39. logger.info(f'{name}由于存在环境变量无法被依赖代理')
  40. return parser.toJs(name,'js',env)
  41. except Exception as e:
  42. return R.error(f'非法猥亵\n{e}')