How to set an external proxy in script?

I’m trying to make a python3.7 script that switches the upstream proxy to an external one for every request that goes trouh the mitm proxy, the structure should look like this:
CLIENT > MITM > EXTERNAL USER:AUTH PROXY > DESTINATION SERVER

This is what i have accomplished so far:

class MITM:

    def request(self, flow):
        if flow.request.method == "CONNECT":
            return

        if flow.live:
            proxy_data = self.switchProxy()
            ctx.log.info('Setting upstream proxy to '+proxy_data.hostname+' and port '+str(proxy_data.port))
            flow.live.change_upstream_proxy_server((proxy_data.hostname, proxy_data.port))
            flow.request.headers["Proxy-Authorization"] = b"Basic"+b" "+base64.b64encode(strutils.always_bytes(proxy_data.username+':'+proxy_data.password))


    def switchProxy(self):
        proxy_data = urlparse('http://user:pass@ip:port')
        return proxy_data


addons = [
    MITM()
]

But this does not seems to work, when i run

mitmdump --upstream http://localhost:8080/ -s mitmserv.py

and make a request trough the mitm proxy to

https://api.ipify.org/?format=json

the returning IP address is my home IP, instead of the external proxy.