Python 序列化 HTTPFlow 对象 (MITM)

Python serialize HTTPFlow object (MITM)

我正在使用 mitmproxy,一个 python HTTP 中间人 (MITM) 代理,来即时修改某个网站的 HTTP 请求。

目标:

出于测试目的,当它收到一个 HTTP 请求时,它应该保存它(它收到一个 HTTPFlow 对象)并且下次发出相同的请求时我需要重新发送完全相同的请求 data/html/header/resourses/ecc.. 到浏览器.

问题:

显而易见的解决方案是序列化对象,但它不可序列化

我不能简单地将它保存在内存中因为我需要在测试期间重新启动代理

我可以做什么来实现我的目标?

详情:

我已经尝试过 picklecPicklemarshal,但出现以下错误:

  • a class that defines __slots__ without defining __getstate__ cannot be pickled

  • can't pickle CDataGCP objects

  • ValueError: unmarshallable object

想法:

找到解决方案(HTTPFlow obj 有一个获取状态的方法)

进口

from mitmproxy.models import HTTPFlow
from mitmproxy.models import HTTPResponse

保存状态:

cached_state = http_flow_response.response.get_state()

加载状态:

# create the obj 
http_response = HTTPResponse(
        cached_state['http_version'], # "HTTP/1.1"
        cached_state['status_code'],  # 200
        cached_state['reason'],       # "Ok"
        cached_state['headers'],      # Headers(content_type="...")
        cached_state['content'])      # str
# send the obj
http_flow_request.reply(cached_http_response)