patch.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # -*- coding: utf-8 -*-
  2. #!/usr/bin/env python
  3. """
  4. 为了方便调测,这里将一些与外部资源有交互的组件进行mock
  5. """
  6. import os
  7. import re
  8. from typing import Union
  9. from django.core.handlers.wsgi import WSGIRequest
  10. from django.http.response import HttpResponse, StreamingHttpResponse, HttpResponseRedirect
  11. from fake.views import fake_view_mapping
  12. PROJECT_ROOT = os.path.join(os.path.abspath(os.path.split(os.path.realpath(__file__))[0] + "/.."))
  13. Response = Union[HttpResponse, StreamingHttpResponse, HttpResponseRedirect]
  14. class PatchMiddleware(object):
  15. def process_view(self, request, view_func, view_args, view_kwargs):
  16. view = view_func.__name__
  17. if view not in fake_view_mapping:
  18. return view_func(request, *view_args, **view_kwargs)
  19. return fake_view_mapping[view](request, *view_args, **view_kwargs)
  20. def process_response(self, request, response):
  21. # type: (WSGIRequest, Response)->Response
  22. if response.streaming:
  23. if request.path == '/user/index.html':
  24. gateway_js_re = re.compile(r'<script src="https.*(?:weixin.+|alipay.+)min\.js"></script>')
  25. script = '<script src="https://cdn.bootcss.com/lodash.js/4.17.11/lodash.min.js"></script>'
  26. script += '<script>'
  27. with open(os.path.join(PROJECT_ROOT, 'fake', 'gateway_patch', 'static', 'bridge.js')) as f:
  28. fake_gateway = f.read()
  29. script += fake_gateway
  30. script += '</script>'
  31. content = gateway_js_re.sub(script, ''.join(response.streaming_content))
  32. response.streaming_content = content
  33. return response
  34. __all__ = ['PatchMiddleware']