How to provide proxy information to Twilio API with Python

时光怂恿深爱的人放手 提交于 2019-12-06 13:27:47

Twilio developer evangelist here.

As the issue on GitHub says, we have switched from urllib2 to Requests but not quite made available all the options, like proxies, in the default TwilioHttpClient. The issue also suggests that you subclass HttpClient to add in the proxy yourself.

As far as I can see, you can just copy the majority of the existing TwilioHttpClient adding the proxies to the session object. Like so:

from requests import Request, Session

from twilio.http import HttpClient, get_cert_file
from twilio.http.response import Response


class ProxiedTwilioHttpClient(HttpClient):
    """
    General purpose HTTP Client for interacting with the Twilio API
    """
    def request(self, method, url, params=None, data=None, headers=None, auth=None, timeout=None,
                allow_redirects=False):

        session = Session()
        session.verify = get_cert_file()
        session.proxies = {
                              "https" : "https://x.x.x.x:yy"
                          }

        request = Request(method.upper(), url, params=params, data=data, headers=headers, auth=auth)

        prepped_request = session.prepare_request(request)
        response = session.send(
            prepped_request,
            allow_redirects=allow_redirects,
            timeout=timeout,
        )

        return Response(int(response.status_code), response.content.decode('utf-8'))

Note the call to session.proxies in the middle of the request method

Then, when you instantiate your Client, include your new ProxiedTwilioHttpClient.

from twilio.rest import Client
from proxied_twilio_http_client import ProxiedTwilioHttpClient

client = Client(account_sid, auth_token, http_client=ProxiedTwilioHttpClient())

Let me know if that helps at all.

@philnash's answer is now out of date, but the good news is that you can get a proxy http-client working with simpler code:

import os
from twilio.rest import Client
from twilio.http.http_client import TwilioHttpClient

proxy_client = TwilioHttpClient()

# assuming your proxy is available via the standard env var https_proxy:
## (this is the case on pythonanywhere)
proxy_client.session.proxies = {'https': os.environ['https_proxy']}

# assumes you've set up your twilio creds as env vars as well
# you can pass these in here alternatively
client = Client(http_client=proxy_client)

# twilio api calls will now work from behind the proxy:
message = client.messages.create(to="...", from_='...', body='...')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!