File: nonblocking.py

package info (click to toggle)
mitmproxy 8.1.1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 38,952 kB
  • sloc: python: 53,389; javascript: 1,603; xml: 186; sh: 105; ansic: 68; makefile: 13
file content (27 lines) | stat: -rw-r--r-- 1,155 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"""
Make events hooks non-blocking using async or @concurrent
"""
import asyncio
import time

from mitmproxy.script import concurrent
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}")


# 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}")