2020-06-22 23:53:39 +00:00
|
|
|
"""
|
2022-02-02 07:40:39 +00:00
|
|
|
Make events hooks non-blocking using async or @concurrent
|
2020-06-22 23:53:39 +00:00
|
|
|
"""
|
2022-02-02 07:40:39 +00:00
|
|
|
import asyncio
|
2013-12-15 01:43:16 +00:00
|
|
|
import time
|
2016-10-27 19:55:24 +00:00
|
|
|
|
2016-02-16 19:49:10 +00:00
|
|
|
from mitmproxy.script import concurrent
|
2022-02-02 07:40:39 +00:00
|
|
|
from mitmproxy import ctx
|
|
|
|
|
|
|
|
|
|
|
|
# Hooks can be async, which allows the hook to call async functions and perform async I/O
|
|
|
|
# without blocking other requests. This is generally preferred for new addons.
|
|
|
|
async def request(flow):
|
|
|
|
ctx.log.info(f"handle request: {flow.request.host}{flow.request.path}")
|
|
|
|
await asyncio.sleep(5)
|
|
|
|
ctx.log.info(f"start request: {flow.request.host}{flow.request.path}")
|
2013-12-15 01:43:16 +00:00
|
|
|
|
2014-09-05 13:16:20 +00:00
|
|
|
|
2022-02-02 07:40:39 +00:00
|
|
|
# Another option is to use @concurrent, which launches the hook in its own thread.
|
|
|
|
# Please note that this generally opens the door to race conditions and decreases performance if not required.
|
|
|
|
# Rename the function below to request(flow) to try it out.
|
|
|
|
@concurrent # Remove this to make it synchronous and see what happens
|
|
|
|
def request_concurrent(flow):
|
2020-04-03 15:18:35 +00:00
|
|
|
# This is ugly in mitmproxy's UI, but you don't want to use mitmproxy.ctx.log from a different thread.
|
2020-11-20 18:25:26 +00:00
|
|
|
print(f"handle request: {flow.request.host}{flow.request.path}")
|
2013-12-15 01:43:16 +00:00
|
|
|
time.sleep(5)
|
2020-11-20 18:25:26 +00:00
|
|
|
print(f"start request: {flow.request.host}{flow.request.path}")
|