Search code examples
pythonpython-3.xtwiliopythonanywhere

PythonAnywhere ConnectionRefusedError: [Errno 111] Connection refused when used with Twilio


I am using PythonAnywhere for running a simple script. It was a trial and I wrote a script that sent me a text message every hour. But every time I run my script it shows an error.

My Script is:

from twilio.rest import TwilioRestClient
from time import sleep

client = TwilioRestClient('AC******************', '**********************')

while True:
    client.messages.create(
        to="+1123456789",
        from_="+1987654321",
        body="Trial.",
    )
    print('Message Sent!')
    sleep(3600)

The error is:

Traceback (most recent call last):
  File "/home/dhruvsomani/sms.py", line 12, in <module>
    body="Trial.",
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/messages.py", line 122, in create
    return self.create_instance(kwargs)
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 341, in create_instance
    data=transform_params(body))
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 193, in request
    resp = make_twilio_request(method, uri, auth=self.auth, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 148, in make_twilio_request
    resp = make_request(method, uri, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 115, in make_request
    resp, content = http.request(url, method, headers=headers, body=data)
  File "/usr/local/lib/python3.4/dist-packages/httplib2/__init__.py", line 1292, in request
    (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
  File "/usr/local/lib/python3.4/dist-packages/httplib2/__init__.py", line 1042, in _request
    (response, content) = self._conn_request(conn, request_uri, method, body, headers)
  File "/usr/local/lib/python3.4/dist-packages/httplib2/__init__.py", line 966, in _conn_request
    conn.connect()
  File "/usr/lib/python3.4/http/client.py", line 1223, in connect
    super().connect()
  File "/usr/lib/python3.4/http/client.py", line 834, in connect
    self.timeout, self.source_address)
  File "/usr/lib/python3.4/socket.py", line 512, in create_connection
    raise err
  File "/usr/lib/python3.4/socket.py", line 503, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

I have not been able to find a solution to this problem. I assure you that the details related to Twilio are correct. This is a PythonAnywhere security error. Please tell me how to overcome this.


Solution

  • PythonAnywhere dev here: we finally worked this one out after much going back and forth -- it appears that the httplib2 library, which the Twilio client library depends on, ignores proxy settings for Python 3.x.

    The solution is to use Python 2.7.