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