mitmproxy/examples/addons/nonblocking.py

28 lines
1.1 KiB
Python
Raw Normal View History

"""
2022-02-02 07:40:39 +00:00
Make events hooks non-blocking using async or @concurrent
"""
2022-02-02 07:40:39 +00:00
import asyncio
import time
2016-10-27 19:55:24 +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}")
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):
# This is ugly in mitmproxy's UI, but you don't want to use mitmproxy.ctx.log from a different thread.
print(f"handle request: {flow.request.host}{flow.request.path}")
time.sleep(5)
print(f"start request: {flow.request.host}{flow.request.path}")