Python try/except not catching exception with requests.get() - python

I'm using Python 3.4 on a Raspberry Pi to upload weather data to a website. Sometime there's a problem uploading (slow Internet or something) and my program crashes. I'm using try/except, but for some reason it's not catching the error. I thought the the last except statement should catch any other errors.
Here's the error:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/urllib3/connectionpool.py", line 343, in _make_request
self._validate_conn(conn)
File "/usr/local/lib/python3.4/dist-packages/urllib3/connectionpool.py", line 839, in _validate_conn
conn.connect()
File "/usr/local/lib/python3.4/dist-packages/urllib3/connection.py", line 344, in connect
ssl_context=context)
File "/usr/local/lib/python3.4/dist-packages/urllib3/util/ssl_.py", line 344, in ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=server_hostname)
File "/usr/lib/python3.4/ssl.py", line 364, in wrap_socket
_context=self)
File "/usr/lib/python3.4/ssl.py", line 577, in __init__
self.do_handshake()
File "/usr/lib/python3.4/ssl.py", line 804, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:584: The handshake operation timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/usr/local/lib/python3.4/dist-packages/urllib3/connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "/usr/local/lib/python3.4/dist-packages/urllib3/util/retry.py", line 367, in increment
raise six.reraise(type(error), error, _stacktrace)
File "/usr/local/lib/python3.4/dist-packages/urllib3/packages/six.py", line 686, in reraise
raise value
File "/usr/local/lib/python3.4/dist-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/usr/local/lib/python3.4/dist-packages/urllib3/connectionpool.py", line 346, in _make_request
self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
File "/usr/local/lib/python3.4/dist-packages/urllib3/connectionpool.py", line 306, in _raise_timeout
raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='rtupdate.wunderground.com', port=443): Read timed out. (read timeout=5)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pi/Weather_Station/WU_upload.py", line 52, in upload2WU
r = requests.get(full_URL, timeout=5) # send data to WU
File "/usr/local/lib/python3.4/dist-packages/requests/api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.4/dist-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/requests/adapters.py", line 529, in send
raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='rtupdate.wunderground.com', port=443): Read timed out. (read timeout=5)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pi/Weather_Station/Weather_Station.py", line 381, in <module>
uploadStatus = WU_upload.upload2WU(suntec, WU_STATION)
File "/home/pi/Weather_Station/WU_upload.py", line 65, in upload2WU
except requests.exceptions.NewConnectionError:
AttributeError: 'module' object has no attribute 'NewConnectionError'
>>>
Here's my code:
try:
r = requests.get(full_URL, timeout=5) # send data to WU
# If uploaded successfully, website will reply with 200
if r.status_code == 200:
return(True)
else:
print('Upload Error: {} {}'.format(r.status_code, r.text))
return(False)
except requests.exceptions.ConnectionError:
print("Upload Error in upload2WU() - ConnectionError")
return(False)
except requests.exceptions.NewConnectionError:
print("Upload Error in upload2WU() - NewConnectionError")
return(False)
except requests.exceptions.ReadTimeout:
print("Upload Error in upload2WU() - ReadTimeout")
return(False)
except requests.exceptions.MaxRetryError:
print("Upload Error in upload2WU() - MaxRetryError")
return(False)
except socket.gaierror:
print("Upload Error in upload2WU() - socket.gaierror")
return(False)
except:
print("Upload Error in upload2WU() - other")
return(False)

Related

Telegram bot parser (TimeoutError: The read operation timed out; ReadTimeoutError)

I'm trying to write a Telegram Messenger bot using telebot that parses the ad page every five seconds and checks if a new ad has appeared.
I change IP address every 10 seconds using Tor. The bot works for a while, but then it crashes. Without a bot, the program works fine. In the same program, but without the bot, exceptions work, but it crashes with the bot.
last_check = ''
have_url = False
#bot.message_handler(content_types=['text'])
def send_text(message):
global have_url
if message.text.lower() == 'create request':
bot.send_message(message.chat.id, 'insert URL')
elif domain in message.text: # Define URL
bot.send_message(message.chat.id, 'Search...')
have_url = True
start_parsing(message)
#bot.message_handler()
def parse(message):
global last_check
olx_url = message.text # Get URL from user
r = get(olx_url, timeout=10, headers=headers, stream=False)
if r.status_code == 200:
'''Parse page and send link to user'''
def start_parsing(url):
while have_url:
try:
parse(url)
except Exception as e:
print(e)
time.sleep(5)
bot.polling(none_stop=True)
After about 20 minutes I get this:
Traceback (most recent call last):
Fileenter code here "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 449, in _make_request
six.raise_from(e, None)
File "<string>", line 3, in raise_from
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 444, in _make_request
httplib_response = conn.getresponse()
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1374, in getresponse
response.begin()
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 318, in begin
version, status, reason = self._read_status()
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 279, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\socket.py", line 705, in readinto
return self._sock.recv_into(b)
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1273, in recv_into
return self.read(nbytes, buffer)
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1129, in read
return self._sslobj.read(len, buffer)
TimeoutError: The read operation timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\adapters.py", line 440, in send
resp = conn.urlopen(
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 785, in urlopen
retries = retries.increment(
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\retry.py", line 550, in increment
raise six.reraise(type(error), error, _stacktrace)
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\packages\six.py", line 770, in reraise
raise value
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen
httplib_response = self._make_request(
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 451, in _make_request
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 340, in _raise_timeout
raise ReadTimeoutError(
urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='api.telegram.org', port=443): Read timed out. (read timeout=25)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\PycharmProjects\notifier\notifier\olx_bot.py", line 95, in <module>
bot.polling(none_stop=True)
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\__init__.py", line 946, in polling
self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\__init__.py", line 1021, in __threaded_polling
raise e
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\__init__.py", line 976, in __threaded_polling
polling_thread.raise_exceptions()
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\util.py", line 116, in raise_exceptions
raise self.exception_info
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\util.py", line 98, in run
task(*args, **kwargs)
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\__init__.py", line 601, in __retrieve_updates
updates = self.get_updates(offset=(self.last_update_id + 1),
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\__init__.py", line 575, in get_updates
json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates, long_polling_timeout)
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\apihelper.py", line 324, in get_updates
return _make_request(token, method_url, params=payload)
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\apihelper.py", line 146, in _make_request
result = _get_req_session().request(
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py", line 529, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py", line 645, in send
r = adapter.send(request, **kwargs)
File "C:\Users\evgen\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\adapters.py", line 532, in send
raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='api.telegram.org', port=443): Read timed out. (read timeout=25)
Process finished with exit code 1
**

An error occurred when downloading files from web using Python

I am new to the Python.I was trying to download a file from a website.This is the URL of the file I need http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
I run my code many times.It alwys works.But sometimes an error will occurr.
Here is my code
import requests
url = 'http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz'
r = requests.get(url, allow_redirects=True,timeout=5)
I learned this from https://www.tutorialspoint.com/downloading-files-from-web-using-python.
The Traceback is
Traceback (most recent call last):
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 445, in _make_request
six.raise_from(e, None)
File "<string>", line 3, in raise_from
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 440, in _make_request
httplib_response = conn.getresponse()
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1371, in getresponse
response.begin()
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 319, in begin
version, status, reason = self._read_status()
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 280, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\socket.py", line 704, in readinto
return self._sock.recv_into(b)
socket.timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\adapters.py", line 439, in send
resp = conn.urlopen(
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 755, in urlopen
retries = retries.increment(
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\util\retry.py", line 532, in increment
raise six.reraise(type(error), error, _stacktrace)
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\packages\six.py", line 770, in reraise
raise value
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 699, in urlopen
httplib_response = self._make_request(
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 447, in _make_request
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 336, in _raise_timeout
raise ReadTimeoutError(
urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host='yann.lecun.com', port=80): Read timed out. (read timeout=5)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\jojo\source\repos\PythonApplication5\PythonApplication5\PythonApplication5.py", line 9, in <module>
r = requests.get(url, allow_redirects=True,timeout=5)
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\api.py", line 76, in get
return request('get', url, params=params, **kwargs)
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 542, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 655, in send
r = adapter.send(request, **kwargs)
File "C:\Users\jojo\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\adapters.py", line 529, in send
raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPConnectionPool(host='yann.lecun.com', port=80): Read timed out. (read timeout=5)
I think it is a network connection error,but I am not sure.If so,how could I avoid it?
SORRY FOR THIS SILLY QUESTION!!!

Google Storage - Read timeout

I am using signed url of in Google Storage. I have a python code using requests that upload a file to the signed url using http PUT. The code is running in a GKE 1.17 deployment with 18 threads on ubuntu 18.04. The code implements retry using the retry python library. In addition the code is crawling websites.
The Problem
The code sometimes fail with the exception ReadTimeout:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 421, in _make_request
six.raise_from(e, None)
File "<string>", line 3, in raise_from
File "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 416, in _make_request
httplib_response = conn.getresponse()
File "/usr/lib/python3.6/http/client.py", line 1346, in getresponse
response.begin()
File "/usr/lib/python3.6/http/client.py", line 307, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.6/http/client.py", line 268, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/lib/python3.6/socket.py", line 586, in readinto
return self._sock.recv_into(b)
File "/usr/lib/python3.6/ssl.py", line 1012, in recv_into
return self.read(nbytes, buffer)
File "/usr/lib/python3.6/ssl.py", line 874, in read
return self._sslobj.read(len, buffer)
File "/usr/lib/python3.6/ssl.py", line 631, in read
v = self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 720, in urlopen
method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
File "/usr/local/lib/python3.6/dist-packages/urllib3/util/retry.py", line 400, in increment
raise six.reraise(type(error), error, _stacktrace)
File "/usr/local/lib/python3.6/dist-packages/urllib3/packages/six.py", line 735, in reraise
raise value
File "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 672, in urlopen
chunked=chunked,
File "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 423, in _make_request
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
File "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 331, in _raise_timeout
self, url, "Read timed out. (read timeout=%s)" % timeout_value
urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='storage.googleapis.com', port=443): Read timed out. (read timeout=30)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
...
response = self.__upload(target, file_stream, headers)
File "<decorator-gen-18>", line 2, in __upload
File "/usr/local/lib/python3.6/dist-packages/retry/api.py", line 74, in retry_decorator
logger)
File "/usr/local/lib/python3.6/dist-packages/retry/api.py", line 33, in __retry_internal
return f()
File "/home/crawler/crawler/upload/UploadResults.py", line 179, in __upload
target, zip_file_stream, headers=headers, timeout=TIMEOUT)
File "/usr/local/lib/python3.6/dist-packages/requests/sessions.py", line 593, in put
return self.request('PUT', url, data=data, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.6/dist-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/requests/adapters.py", line 529, in send
raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='storage.googleapis.com', port=443): Read timed out. (read timeout=30)
This means that the connection was made successfully and no data was received in the readtimeout window.
My Attempts To Fix It
More retries - Up to 10
Larger delay between retries
exponential backoff
Test if I raise ReadTimeout() in the function if the functions retries this specific exception, and it did.
Allow more connections in for the session and allow more connections per host.
The google storage url is avoiding naming bottleneck by using a different folder for each file.
Larger read timeout value - tried with up to 60 seconds.
My Code
import requests
from google.api_core.exceptions import GatewayTimeout, GoogleAPICallError, ServiceUnavailable
from requests.exceptions import ConnectionError
from crawler.exceptions.CrawlerException import CrawlerException, eCrawlingStatusCodes
from retry import retry
RETRIES = 10
BACKOFF = 1.5
DELAY = 2
TIMEOUT = (9.05, 30)
class UploadResults:
GOOGLE_STORAGE = GoogleStorage()
SESSION = requests.Session()
SESSION.mount('https://', requests.adapters.HTTPAdapter(
pool_connections=20, pool_maxsize=30))
#retry(exceptions=(CrawlerException, requests.exceptions.RequestException, ValueError,
requests.exceptions.Timeout, requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout),
tries=RETRIES, delay=DELAY, backoff=BACKOFF)
def __upload(self, target, zip_file_stream, headers):
response = UploadResults.SESSION.put(
target, zip_file_stream, headers=headers, timeout=TIMEOUT)
if response.status_code >= 300:
raise CrawlerException(eCrawlingStatusCodes.InternalError,
"Internal error on uploading to path, Server status: %d" % response.status_code)
return response
Questions
What can cause this exception?
Is there a limit I am missing that can cause this behaviour?

I was stuck on Exception Handling in Python Requests

Contributors.
I'm writing a get title of web program using python requests module.
I wanna do error handling, but i was stuck.
This is my code.
for i in result:
try:
print("URL : {}".format(i[0]))
req = requests.get(i[0], headers=headers, timeout=15)
html = req.text
soup = BeautifulSoup(html, 'html.parser')
title = soup.title.string
print(title)
except requests.ConnectionError as e:
print("Error : Network Connection Error <{}>".format(e))
except requests.Response.raise_for_status() as e:
print("Error: Invalid Response Error.")
except requests.exceptions.Timeout as e:
print("Error: Timeout Error.")
except requests.TooManyRedirects as e:
print("Error: Too many Redirects")
except:
print("Error: Unknown Error.")
This is Python Console's Answers:
URL : url.com
Nice URL
URL : http://0x92B9BDB9
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 387, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/usr/lib/python3.4/http/client.py", line 1088, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python3.4/http/client.py", line 1126, in _send_request
self.endheaders(body)
File "/usr/lib/python3.4/http/client.py", line 1084, in endheaders
self._send_output(message_body)
File "/usr/lib/python3.4/http/client.py", line 922, in _send_output
self.send(msg)
File "/usr/lib/python3.4/http/client.py", line 857, in send
self.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)
socket.timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 330, in send
timeout=timeout
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 562, in urlopen
body=body, headers=headers)
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 391, in _make_request
(self.host, timeout_obj.connect_timeout))
urllib3.exceptions.ConnectTimeoutError: (<urllib3.connectionpool.HTTPConnectionPool object at 0x7f0e820c69b0>, 'Connection to 0x92B9BDB9 timed out. (connect timeout=15)')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "gettitle.py", line 49, in <module>
req = requests.get(i[0], headers=headers, timeout=15)
File "/usr/lib/python3/dist-packages/requests/api.py", line 55, in get
return request('get', url, **kwargs)
File "/usr/lib/python3/dist-packages/requests/api.py", line 44, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 455, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 558, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 387, in send
raise Timeout(e)
requests.exceptions.Timeout: (<urllib3.connectionpool.HTTPConnectionPool object at 0x7f0e820c69b0>, 'Connection to 0x92B9BDB9 timed out. (connect timeout=15)')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "gettitle.py", line 58, in <module>
except requests.Response.raise_for_status() as e:
TypeError: raise_for_status() missing 1 required positional argument: 'self'
How can i fix it?
Thanks so much for letting me know!
I had the same problem with request.get, I kept having the same problem like you did. I found out that I was using my VPN. When I turned it off everything got back to normal!

Why do I get occasional timeout errors when retrieving specific images with Python Requests?

This problem happens rarely, i.e. only with specific images. How should I avoid it?
this does work:
response = requests.get(url='http://1.bp.blogspot.com/-XFloD6F3Tws/VPW9r8e3fzI/AAAAAAAH77c/izzZRWSbGdk/s1600/16467_1197957903548615_3921728777903612927_n.jpg', stream=True, timeout=60)
response.text
but this does not:
response = requests.get(url='http://1.bp.blogspot.com/-6SnMAxnWLKM/VPTIf5AMcDI/AAAAAAAH7zA/wNRxXAcH_e4/s1600/Ανώνυμο-1.jpg', stream=True, timeout=60)
response.text
in fact, it returns the following error:
Traceback (most recent call last):
File "/home/eualin/.bin/anaconda3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 186, in read
data = self._fp.read(amt)
File "/home/eualin/.bin/anaconda3/lib/python3.4/http/client.py", line 500, in read
return super(HTTPResponse, self).read(amt)
File "/home/eualin/.bin/anaconda3/lib/python3.4/http/client.py", line 539, in readinto
n = self.fp.readinto(b)
File "/home/eualin/.bin/anaconda3/lib/python3.4/socket.py", line 371, in readinto
return self._sock.recv_into(b)
socket.timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/eualin/.bin/anaconda3/lib/python3.4/site-packages/requests/models.py", line 638, in generate
for chunk in self.raw.stream(chunk_size, decode_content=True):
File "/home/eualin/.bin/anaconda3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 256, in stream
data = self.read(amt=amt, decode_content=decode_content)
File "/home/eualin/.bin/anaconda3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 201, in read
raise ReadTimeoutError(self._pool, None, 'Read timed out.')
requests.packages.urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host='1.bp.blogspot.com', port=80): Read timed out.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/eualin/.bin/anaconda3/lib/python3.4/site-packages/requests/models.py", line 734, in text
if not self.content:
File "/home/eualin/.bin/anaconda3/lib/python3.4/site-packages/requests/models.py", line 707, in content
self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
File "/home/eualin/.bin/anaconda3/lib/python3.4/site-packages/requests/models.py", line 645, in generate
raise ConnectionError(e)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='1.bp.blogspot.com', port=80): Read timed out.
EDIT
This is the error I get when I apply .encode("utf-8") on the url string.
>>> response = requests.get(url='http://1.bp.blogspot.com/-6SnMAxnWLKM/VPTIf5AMcDI/AAAAAAAH7zA/wNRxXAcH_e4/s1600/Ανώνυμο-1.jpg'.encode("utf-8"), stream=True, timeout=60)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/eualin/.bin/anaconda3/lib/python3.4/site-packages/requests/api.py", line 59, in get
return request('get', url, **kwargs)
File "/home/eualin/.bin/anaconda3/lib/python3.4/site-packages/requests/api.py", line 48, in request
return session.request(method=method, url=url, **kwargs)
File "/home/eualin/.bin/anaconda3/lib/python3.4/site-packages/requests/sessions.py", line 451, in request
resp = self.send(prep, **send_kwargs)
File "/home/eualin/.bin/anaconda3/lib/python3.4/site-packages/requests/sessions.py", line 551, in send
adapter = self.get_adapter(url=request.url)
File "/home/eualin/.bin/anaconda3/lib/python3.4/site-packages/requests/sessions.py", line 630, in get_adapter
raise InvalidSchema("No connection adapters were found for '%s'" % url)
requests.exceptions.InvalidSchema: No connection adapters were found for 'b'http://1.bp.blogspot.com/-6SnMAxnWLKM/VPTIf5AMcDI/AAAAAAAH7zA/wNRxXAcH_e4/s1600/\xce\x91\xce\xbd\xcf\x8e\xce\xbd\xcf\x85\xce\xbc\xce\xbf-1.jpg''
>>>

Categories

Resources