'403 when requesting Image URL in Python - works locally but not on PythonAnywhere

I'm trying to write a twitter bot using Python that just tweets images on a schedule and selects a random one from an array of URLs. I'm hosting the images on imgbb.com and using tweepy to tweet.

My code works when run from terminal on my local machine, but I'm now trying to get it deployed by running it on Python Anywhere. Here I get a 403 request when trying to get the image.

Method to get images:

def tweet_image(url, message):
    filename = 'temp.jpg'
    request = requests.get(url, stream=True)
    if request.status_code == 200:
        with open(filename, 'wb') as image:
            for chunk in request:
                image.write(chunk)

        api.update_with_media(filename, status=message)
        os.remove(filename)
    else:
        print("Unable to download image")

Error returned:

File "/home/user/.virtualenvs/my-virtualenv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 727, in urlopen
    method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
  File "/home/user/.virtualenvs/my-virtualenv/lib/python3.6/site-packages/urllib3/util/retry.py", line 439, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='i.ibb.co', port=443): Max retries exceeded with url: /4gJLdfw/images-12.jpg (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connect
ion failed: 403 Forbidden',)))

Do I need to set some kind of user agent or request headers for the GET to succeed? I'm completely new to python.



Solution 1:[1]

You have probably a free account on PythonAnywhere thus having a limited access to the outside world. You may check the whitelisted domains here. I see that i.ibb.co redirects to imgbb.com which has a whitelisted api so maybe you should try that domain instead.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1