How to replace the whole response with a content coming from a different URL

I am new to mitmproxy and to python, sorry in advance for any inaccuracy.

I am trying to replace the whole response with a new one coming from a different url on certain conditions.
Simplifying things, if the request contains mydomain/some/thing I want to show the original response,
but if the request contains mydomain/replace/me I want to replace the response with the content
coming from mydomain.local/replace/me
Only the response content needs to change, not the requested url.

I tried a small script

import requests
url = “example”
r = requests.get(url)
print(r.text)

and it works fine if I type

phyton myscript

However if I try to change a little bit the script to be used in mitmproxy as a myrules script file

import requests
from mitmproxy import ctx, http

def request(flow):
if “mydomain” in flow.request.host:
ctx.log.info(“Found”)
url = “example”
r = requests.get(url)
ctx.log.info(r.text)

and launch mitmproxy with:

mitmproxy -s myrules

mitmproxy shows my traffic, however as soon as I type mydomain in the browser it get stuck

What am I doing wrong?
Thanks in advance!

$ mitmproxy --version
Mitmproxy version: 2.0.2 (release version)
Python version: 3.6.2
Platform: Darwin-15.6.0-x86_64-i386-64bit
SSL version: OpenSSL 1.1.0f 25 May 2017
Mac version: 10.11.6 (‘’, ‘’, ‘’) x86_64

$ python3 --version
Python 3.6.2

$ pip3 --version
pip 9.0.1 from /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (python 3.6)