Custom Exception not caught in Python Flask App - python

I got a Flask app calling different modules. One of them eventually raises a NoPrice exception but the except NoPrice doesn't catch it as a NoPrice but except Exceptioncatches it...
class NoPrice(Exception):
pass
somewhere in a module
raise NoPrice('error')
in my flask app
try:
raise NoPrice('main')
except NoPrice as e:
print('main')
except Exception as e:
print('main2')
try:
resp = alicia.create_predictions(select)
except NoPrice as e:
print('main3')
except Exception as e:
print('main4')
print(repr(e))
print(e)
print(traceback.format_exc())
The output of this is
main
main4
NoPrice('No price found for material_reference 0148054b-e681-4fb6-9722-946f3cfa8529 the weight 1.7471266917293233', 'occurred at index 0')
('No price found for material_reference 0148054b-e681-4fb6-9722-946f3cfa8529 the weight 1.7471266917293233', 'occurred at index 0')
Traceback (most recent call last):
File "c/main.py", line 71, in create_predictions_api
resp = alicia.create_predictions(select)
File "/absolutepath/app/alicia.py", line 703, in create_predictions
self.set_machines_and_format()
File "/absolutepath/app/alicia.py", line 574, in set_machines_and_format
x["is_screenprinting_option"]), axis = 1)
File "/absolutepath/venv/lib/python3.7/site-packages/pandas/core/frame.py", line 6913, in apply
return op.get_result()
File "/absolutepath/venv/lib/python3.7/site-packages/pandas/core/apply.py", line 186, in get_result
return self.apply_standard()
File "/absolutepath/venv/lib/python3.7/site-packages/pandas/core/apply.py", line 292, in apply_standard
self.apply_series_generator()
File "/absolutepath/venv/lib/python3.7/site-packages/pandas/core/apply.py", line 321, in apply_series_generator
results[i] = self.f(v)
File "/absolutepath/app/alicia.py", line 574, in <lambda>
x["is_screenprinting_option"]), axis = 1)
File "/absolutepath/app/alicia.py", line 359, in predict_price_relying_on_format
output = Jerome(self.product, self.hipe_client_config).run(self.quote_input)
File "/absolutepath/app/jerome/jerome.py", line 235, in run
pliant = pliant_obj.price(quote_input, self.material_reference)
File "/absolutepath/app/jerome/options_construction/pliant.py", line 66, in price
quote_input['matter_margin_percentage'])
File "/absolutepath/app/jerome/options_construction/pliant.py", line 52, in pliant
raise NoPrice(f"No price found for material_reference {material_reference.id} the weight {x1}")
exceptions.NoPrice: ('No price found for material_reference 0148054b-e681-4fb6-9722-946f3cfa8529 the weight 1.7471266917293233', 'occurred at index 0')
Why doesn't the except NoPrice catch my exception ?
Shouldn't the ouput be
main
main3
My goal is ultimately to handle only my NoPrice exception

my_function must not be raising the NoPrice exception, and therefore it isn't caught in the 'main 3' section.

Related

what is the idiomatic way to raise an exception within the exception handler in Python?

What is the correct way in Python of catching an exception, and raising another exception? I.e, I want to catch an exception of type 1, manipulate the Exception object and unconditionally raise a second exception of type 2, so that the calling function doesn't see the Exception of type 1 but absolutely sees the exception of type 2 whose construction depends on data accessed from the type-1 Exception.
Here is the code I've tried which doesn't work.
def d(wrt):
try:
return rt.derivative(wrt).canonicalize()
except CannotComputeDerivative as e:
msg = "\n".join([f"When generating derivatives from {self}",
f" when computing edges of {rt}",
f" which canonicalizes to {self.canonicalize()}",
f" computing derivative of {e.rte}",
f" wrt={e.wrt}",
f" derivatives() reported: {e.msg}"])
raise CannotComputeDerivatives(msg=msg,
rte=rt,
wrt=wrt,
first_types=fts,
mdtd=wrts)
The reason I think it doesn't work is because I get the following message as output:
Error
Traceback (most recent call last):
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py", line 95, in d
return rt.derivative(wrt).canonicalize()
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_singleton.py", line 68, in derivative
return super().derivative(wrt)
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py", line 72, in derivative
return self.derivative_down(wrt)
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_singleton.py", line 91, in derivative_down
raise CannotComputeDerivative(
rte.r_rte.CannotComputeDerivative
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/jnewton/Repos/python-rte/pyrte/tests/rte_tests.py", line 615, in test_derivatives
self.assertTrue(rt.derivatives())
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py", line 111, in derivatives
return trace_graph(self, edges)
File "/Users/jnewton/Repos/python-rte/pyrte/genus/utils.py", line 199, in trace_graph
es = edges(v0) # List[(L,V)]
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py", line 109, in edges
return [(td, d(td)) for td in wrts]
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py", line 109, in <listcomp>
return [(td, d(td)) for td in wrts]
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py", line 103, in d
raise CannotComputeDerivatives(msg=msg,
rte.r_rte.CannotComputeDerivatives
Following the suggestion of MisterMiyagi I added from None after the raise CannotComputeDerivatives(...). This makes progress, but it seems the unittest environment doesn't really like it. The displayed message during unit testing is shown below. It looks like unittest sadly truncates the message.
Error
Traceback (most recent call last):
File "/Users/jnewton/Repos/python-rte/pyrte/tests/rte_tests.py", line 615, in test_derivatives
rt.derivatives()
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py", line 111, in derivatives
return trace_graph(self, edges)
File "/Users/jnewton/Repos/python-rte/pyrte/genus/utils.py", line 199, in trace_graph
es = edges(v0) # List[(L,V)]
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py", line 109, in edges
return [(td, d(td)) for td in wrts]
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py", line 109, in <listcomp>
return [(td, d(td)) for td in wrts]
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py", line 103, in d
raise CannotComputeDerivatives(msg=msg,
rte.r_rte.CannotComputeDerivatives
=============
To follow up on the solution:
The original problem was that the __init__ function for the CannotComputeDerivatives class was calling super().__init__() without passing the message string. I've updated the class definition as follows.
class CannotComputeDerivatives(Exception):
def __init__(self, msg, rte, wrt, first_types, mdtd):
self.msg = msg
self.rte = rte
self.wrt = wrt
self.first_types = first_types
self.mdtd = mdtd
super().__init__(msg)
The result is that I get beautiful error messages during unit testing:
Error
Traceback (most recent call last):
File "/Users/jnewton/Repos/python-rte/pyrte/tests/rte_tests.py", line 615, in test_derivatives
self.assertTrue(rt.derivatives())
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py", line 111, in derivatives
return trace_graph(self, edges)
File "/Users/jnewton/Repos/python-rte/pyrte/genus/utils.py", line 199, in trace_graph
es = edges(v0) # List[(L,V)]
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py", line 109, in edges
return [(td, d(td)) for td in wrts]
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py", line 109, in <listcomp>
return [(td, d(td)) for td in wrts]
File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py", line 103, in d
raise CannotComputeDerivatives(msg=msg,
rte.r_rte.CannotComputeDerivatives: When generating derivatives from Singleton(SOr(odd?, SAtomic(Test2)))
when computing edges of Singleton(SOr(odd?, SAtomic(Test2)))
which canonicalizes to Singleton(SOr(odd?, SAtomic(Test2)))
computing derivative of Singleton(SOr(odd?, SAtomic(Test2)))
wrt=SOr(SAtomic(Test2), odd?)
derivatives() reported: Singleton.derivative_down cannot compute derivative of Singleton(SOr(odd?, SAtomic(Test2)))
wrt=SOr(SAtomic(Test2), odd?)
disjoint=False
subtypep=None
Thanks #MisterMiyagi for the suggestion to add from None after the raise .... This averts the problem that the system complains about exception within exception.

How to handle error: Task exception was never retrieved

While scanning bunch of websites using the below function I received an error (see below). Would there be any except step I should add to the function below to handle such error or there is something wrong with my try / except part in my function?
function:
import pandas as pd
import requests
from bs4 import BeautifulSoup
import re
import io
import requests.exceptions
import time
import asyncio
from concurrent.futures import ProcessPoolExecutor, as_completed
import io
df = pd.read_csv('myScan.csv')
urls = df.T.values.tolist()[2]
results = {}
status = {}
async def scrape(url):
try:
r = requests.get(url, timeout=(3, 6))
r.raise_for_status()
soup = BeautifulSoup(r.content, 'html.parser')
if soup.body:
data = {
"coming soon": soup.body.findAll(text = re.compile("coming soon", re.I)),
"Opening Soon": soup.body.findAll(text = re.compile("Opening Soon", re.I)),
"Under Construction": soup.body.findAll(text = re.compile("Under Construction", re.I)),
"Currently Unavailable": soup.body.findAll(text = re.compile("Currently Unavailable", re.I)),
"button_2": soup.findAll(text = re.compile('button_2.js'))}
results[url] = data
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout, requests.exceptions.MissingSchema):
status[url] = "Connection Error"
except (requests.exceptions.HTTPError):
status[url] = "Http Error"
except (requests.exceptions.TooManyRedirects):
status[url] = "Redirects"
except (requests.exceptions.RequestException) as err:
status[url] = "Fatal Error: " + err + url
else:
status[url] = "OK"
async def main():
await asyncio.wait([scrape(url) for url in urls])
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
comingList= []
openingList = []
underList = []
button_2 = []
statusList = []
for url in urls:
if(not results.get(url)):
statusList.append(status.get(url))
comingList.append("-")
openingList.append("-")
underList.append("-")
button_2.append("-")
else:
statusList.append(status.get(url))
comingList.append("x" if len(results[url].get("coming soon")) > 0 else "-")
openingList.append("x" if len(results[url].get("Opening Soon")) > 0 else "-")
underList.append("x" if len(results[url].get("Under Construction")) > 0 else "-")
button_2.append("x" if len(results[url].get("button_2")) > 0 else "-")
df["comingSoon"] = pd.DataFrame(comingList, columns=['comingSoon'])
df["openingSoon"] = pd.DataFrame(openingList, columns=['openingSoon'])
df["underConstruction"] = pd.DataFrame(underList, columns=['underConstruction'])
df["button_2"] = pd.DataFrame(button_2, columns=['button_2'])
df['status'] = pd.DataFrame(statusList, columns=['Status'])
df.to_csv('myScanCompleted.csv', index=False)
Error:
Task exception was never retrieved
future: <Task finished name='Task-43943' coro=<scrape() done, defined at crawler.py:69> exception=TypeError('can only concatenate str (not "ChunkedEncodingError") to str')>
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/urllib3/response.py", line 697, in _update_chunk_length
self.chunk_left = int(line, 16)
ValueError: invalid literal for int() with base 16: b''
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/urllib3/response.py", line 438, in _error_catcher
yield
File "/usr/local/lib/python3.9/site-packages/urllib3/response.py", line 764, in read_chunked
self._update_chunk_length()
File "/usr/local/lib/python3.9/site-packages/urllib3/response.py", line 701, in _update_chunk_length
raise InvalidChunkLength(self, line)
urllib3.exceptions.InvalidChunkLength: InvalidChunkLength(got length b'', 0 bytes read)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/requests/models.py", line 753, in generate
for chunk in self.raw.stream(chunk_size, decode_content=True):
File "/usr/local/lib/python3.9/site-packages/urllib3/response.py", line 572, in stream
for line in self.read_chunked(amt, decode_content=decode_content):
File "/usr/local/lib/python3.9/site-packages/urllib3/response.py", line 793, in read_chunked
self._original_response.close()
File "/usr/local/Cellar/python#3.9/3.9.0_5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py", line 135, in __exit__
self.gen.throw(type, value, traceback)
File "/usr/local/lib/python3.9/site-packages/urllib3/response.py", line 455, in _error_catcher
raise ProtocolError("Connection broken: %r" % e, e)
urllib3.exceptions.ProtocolError: ("Connection broken: InvalidChunkLength(got length b'', 0 bytes read)", InvalidChunkLength(got length b'', 0 bytes read))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "crawler.py", line 71, in scrape
r = requests.get(url, timeout=(3, 6))
File "/usr/local/lib/python3.9/site-packages/requests/api.py", line 76, in get
return request('get', url, params=params, **kwargs)
File "/usr/local/lib/python3.9/site-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python3.9/site-packages/requests/sessions.py", line 542, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.9/site-packages/requests/sessions.py", line 697, in send
r.content
File "/usr/local/lib/python3.9/site-packages/requests/models.py", line 831, in content
self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b''
File "/usr/local/lib/python3.9/site-packages/requests/models.py", line 756, in generate
raise ChunkedEncodingError(e)
requests.exceptions.ChunkedEncodingError: ("Connection broken: InvalidChunkLength(got length b'', 0 bytes read)", InvalidChunkLength(got length b'', 0 bytes read))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "crawler.py", line 89, in scrape
status[url] = "Fatal Error: " + err + url
TypeError: can only concatenate str (not "ChunkedEncodingError") to str
I encountered the same error. Can't speak as to why, but switching from the html.parser parser to lxml fixed it for me.
Might be useful: difference between parsers

Dynamically extend exception with custom exception in Python?

Let's say I have a special exception that does some neat and wonderful things - Solving world hunger, good will toward men, logging, etc:
class SpecialException(Exception):
# Does something really neat here.
pass
Now let's say that an exception may be raised, but we don't know what type of exception we'll encounter:
def crashAndBurn():
try:
import random
choice = random.choice([1,2])
if choice == 1:
int('asdf') # Can't cast string to int: ValueError.
else:
x # Variable `x` doesn't exist: NameError.
except Exception as e:
# Code to wrap `e` into `SpecialException` class
raise e
When that unknown type of exception is raised, we want to catch it, wrap it in our SpecialException class, and raise it so it can be caught either by the original type of exception thrown, or by catching SpecialException:
try:
crashAndBurn()
except ValueError as e:
print('This time it was a ValueError, and we want to handle this differently for some reason')
except SpecialException as e:
print('Handle this more generically')
Any recommendations on how to (reasonably) solve this?
In summary, we need:
Ability to catch exception originally raised, and ability to catch SpecialException
Retain traceback for easy debugging
Contain the original exception's error message
What I've Tried:
Tried using raise SpecialException from e. While we are able to view the error message and traceback from the originally raised exception, we are no longer able to catch it by the type of exception originally thrown... Eg: We can catch SpecialException, but can't catch ValueError:
def crashAndBurn():
try:
int('asdf') # ValueError
except Exception as e:
raise SpecialException('Special Exception Encountered').with_traceback(e.__traceback__) from e
try:
crashAndBurn()
except ValueError as e:
print('This will never be encountered')
except SpecialException as e:
print('This will be encountered, when we wanted it to be handled above')
The closest we've gotten technically fulfills our needs, however:
While the exception raised can be caught as either SpecialException or ValueError, it's actually raised as another, one-time use class: DynamicSpecialException
It's really gross and seemingly very un-pythonic
def crashAndBurn():
try:
int('asdf') # ValueError
except Exception as e:
class DynamicSpecialException(SpecialException, e.__class__):
pass # I feel dirty
raise DynamicSpecialException('Special Exception Encountered').with_traceback(e.__traceback__)
try:
crashAndBurn()
except ValueError as e:
print('Caught as a ValueError!')
try:
crashAndBurn()
except SpecialException as e:
print('Caught as SpecialException!')
What I was really expecting to find was something similar to raise e.extend(SpecialException) or raise SpecialException.from(e) - rather than this rabbit hole I've seemingly wiggled my way down today! :)
Here's a bit of a stab at it. It seems to do most of what you want, except that it appends the stack trace of the specialfactory handling.
The thing I learned is that you can't swap the exception class, e.__class__ = <dynamic class>, you have to create a new one and raise it.
import pdb
from traceback import print_exc as xp
import sys
def cpdb():
""" put `pdb` on commmand line to halt execution in debugger """
return "pdb" in sys.argv
class SpecialException(Exception):
def solve_world_hunger(self):
print(f"eat more 🦄")
def specialfactory(e):
""" creates a class dynamically and keeps the original as a base"""
cls_ = type("SpecialException", (SpecialException, e.__class__),{})
e2 = cls_(str(e))
e2.ori = e
e2.__dict__.update(**e.__dict__)
# 👇 you can try different flavors to see what changes:
# basically, I haven't found a way to suppress `The above exception was the direct cause of the following exception:`
# see also https://stackoverflow.com/questions/33809864/disable-exception-chaining-in-python-3
# return e2
# raise e2. raise specialfactory(e).with_traceback(e.__traceback__) from e
# raise e2 from e
raise e2.with_traceback(e.__traceback__) from e
def crashAndBurn(no_special=False, custom_message=None):
try:
if custom_message:
exc = ValueError(custom_message)
exc.foo = "bar"
raise exc
int('asdf') # ValueError
except Exception as e:
if no_special:
#just to investigate what things look like for a plain ValueError
raise
# raise specialfactory(e).with_traceback(e.__traceback__) from e
raise specialfactory(e) from e
#################################################################
# check what a regular unchanged ValueError looks like
#################################################################
try:
print("\n\n\n🔬regular ValueError, unchanged")
crashAndBurn(no_special=1)
except ValueError as e:
if cpdb(): pdb.set_trace()
print(f' plain ValueError: {e}')
xp()
except SpecialException as e:
if cpdb(): pdb.set_trace()
print(f' Caught as a SpecialException!: {e}')
xp()
#################################################################
# catch a Special as a ValueError
#################################################################
try:
print("\n\n\n🔬ValueError ")
crashAndBurn()
except ValueError as e:
if cpdb(): pdb.set_trace()
print(f' Caught as a ValueError! {e}')
xp()
except SpecialException as e:
if cpdb(): pdb.set_trace()
print(f' Caught as a SpecialException! {e}')
xp()
#################################################################
# catch a Special
#################################################################
try:
print("\n\n\n🔬SpecialException handling")
crashAndBurn()
except SpecialException as e:
if cpdb(): pdb.set_trace()
print(f' Caught as a SpecialException! {e} {e.solve_world_hunger()}')
xp()
except ValueError as e:
if cpdb(): pdb.set_trace()
print(f' Caught as a ValueError! {e}')
xp()
#################################################################
# custom variables are still available
#################################################################
try:
print("\n\n\n🔬ValueError with custom_message/content ")
crashAndBurn(custom_message="my custom_message")
except SpecialException as e:
if cpdb(): pdb.set_trace()
print(f' Caught as a SpecialException! {e} {e.foo=} {e.solve_world_hunger()}')
xp()
except ValueError as e:
if cpdb(): pdb.set_trace()
print(f' Caught as a ValueError! {e}')
xp()
output:
Traceback (most recent call last):
File "test_183.py", line 57, in <module>
crashAndBurn(no_special=1)
File "test_183.py", line 41, in crashAndBurn
int('asdf') # ValueError
ValueError: invalid literal for int() with base 10: 'asdf'
Traceback (most recent call last):
File "test_183.py", line 41, in crashAndBurn
int('asdf') # ValueError
ValueError: invalid literal for int() with base 10: 'asdf'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "test_183.py", line 74, in <module>
crashAndBurn()
File "test_183.py", line 47, in crashAndBurn
raise specialfactory(e) from e
File "test_183.py", line 30, in specialfactory
raise e2.with_traceback(e.__traceback__) from e
File "test_183.py", line 41, in crashAndBurn
int('asdf') # ValueError
SpecialException: invalid literal for int() with base 10: 'asdf'
Traceback (most recent call last):
File "test_183.py", line 41, in crashAndBurn
int('asdf') # ValueError
ValueError: invalid literal for int() with base 10: 'asdf'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "test_183.py", line 92, in <module>
crashAndBurn()
File "test_183.py", line 47, in crashAndBurn
raise specialfactory(e) from e
File "test_183.py", line 30, in specialfactory
raise e2.with_traceback(e.__traceback__) from e
File "test_183.py", line 41, in crashAndBurn
int('asdf') # ValueError
SpecialException: invalid literal for int() with base 10: 'asdf'
Traceback (most recent call last):
File "test_183.py", line 39, in crashAndBurn
raise exc
ValueError: my custom_message
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "test_183.py", line 108, in <module>
crashAndBurn(custom_message="my custom_message")
File "test_183.py", line 47, in crashAndBurn
raise specialfactory(e) from e
File "test_183.py", line 30, in specialfactory
raise e2.with_traceback(e.__traceback__) from e
File "test_183.py", line 39, in crashAndBurn
raise exc
SpecialException: my custom_message
🔬regular ValueError, unchanged
plain ValueError: invalid literal for int() with base 10: 'asdf'
🔬ValueError
Caught as a ValueError! invalid literal for int() with base 10: 'asdf'
🔬SpecialException handling
eat more 🦄
Caught as a SpecialException! invalid literal for int() with base 10: 'asdf' None
🔬ValueError with custom_message/content
eat more 🦄
Caught as a SpecialException! my custom_message e.foo='bar' None

Python: RecursionError: maximum recursion depth exceeded while calling a Python object

The code i've been buidling came across this error today and i cant figure out whats wrong and why its happening.
The error:
Traceback (most recent call last):
File "D:/Drive/Outros/Python/Projects/Simple_Dict_bot.py", line 63, in loop
last_msg()
File "D:/Drive/Outros/Python/Projects/Simple_Dict_bot.py", line 35, in last_msg
loop()
File "D:/Drive/Outros/Python/Projects/Simple_Dict_bot.py", line 63, in loop
last_msg()
File "D:/Drive/Outros/Python/Projects/Simple_Dict_bot.py", line 35, in last_msg
loop()
File "D:/Drive/Outros/Python/Projects/Simple_Dict_bot.py", line 61, in loop
open_chatroom()
File "D:/Drive/Outros/Python/Projects/Simple_Dict_bot.py", line 21, in open_chatroom
WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, '_1ZMSM')))
File "D:\py\lib\site-packages\selenium\webdriver\support\wait.py", line 71, in until
value = method(self._driver)
File "D:\py\lib\site-packages\selenium\webdriver\support\expected_conditions.py", line 64, in __call__
return _find_element(driver, self.locator)
File "D:\py\lib\site-packages\selenium\webdriver\support\expected_conditions.py", line 411, in _find_element
return driver.find_element(*by)
File "D:\py\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
'value': value})['value']
File "D:\py\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 319, in execute
response = self.command_executor.execute(driver_command, params)
File "D:\py\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 374, in execute
return self._request(command_info[0], url, body=data)
File "D:\py\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 397, in _request
resp = self._conn.request(method, url, body=body, headers=headers)
File "D:\py\lib\site-packages\urllib3\request.py", line 80, in request
method, url, fields=fields, headers=headers, **urlopen_kw
File "D:\py\lib\site-packages\urllib3\request.py", line 171, in request_encode_body
return self.urlopen(method, url, **extra_kw)
File "D:\py\lib\site-packages\urllib3\poolmanager.py", line 330, in urlopen
response = conn.urlopen(method, u.request_uri, **kw)
File "D:\py\lib\site-packages\urllib3\connectionpool.py", line 672, in urlopen
chunked=chunked,
File "D:\py\lib\site-packages\urllib3\connectionpool.py", line 421, in _make_request
six.raise_from(e, None)
File "<string>", line 3, in raise_from
File "D:\py\lib\site-packages\urllib3\connectionpool.py", line 416, in _make_request
httplib_response = conn.getresponse()
File "D:\py\lib\http\client.py", line 1321, in getresponse
response.begin()
File "D:\py\lib\http\client.py", line 320, in begin
self.headers = self.msg = parse_headers(self.fp)
File "D:\py\lib\http\client.py", line 214, in parse_headers
return email.parser.Parser(_class=_class).parsestr(hstring)
File "D:\py\lib\email\parser.py", line 68, in parsestr
return self.parse(StringIO(text), headersonly=headersonly)
File "D:\py\lib\email\parser.py", line 57, in parse
feedparser.feed(data)
File "D:\py\lib\email\feedparser.py", line 176, in feed
self._call_parse()
File "D:\py\lib\email\feedparser.py", line 180, in _call_parse
self._parse()
File "D:\py\lib\email\feedparser.py", line 295, in _parsegen
if self._cur.get_content_maintype() == 'message':
File "D:\py\lib\email\message.py", line 594, in get_content_maintype
ctype = self.get_content_type()
File "D:\py\lib\email\message.py", line 578, in get_content_type
value = self.get('content-type', missing)
File "D:\py\lib\email\message.py", line 471, in get
return self.policy.header_fetch_parse(k, v)
File "D:\py\lib\email\_policybase.py", line 316, in header_fetch_parse
return self._sanitize_header(name, value)
File "D:\py\lib\email\_policybase.py", line 287, in _sanitize_header
if _has_surrogates(value):
File "D:\py\lib\email\utils.py", line 57, in _has_surrogates
s.encode()
RecursionError: maximum recursion depth exceeded while calling a Python object
Process finished with exit code 1
This will get the last unread message.
def w:
try:
post = driver.find_elements_by_class_name("_12pGw")
ultimo = len(post) - 1
texto = post[ultimo].find_element_by_css_selector(
"span.selectable-text").text
return texto
except Exception:
loop()
This creates a dictionary from a pandas df and replies the user with matching answer.
def y:
df = pd.read_excel(r'D:\Drive\Outros\Python\Project\Dict.xlsx', error_bad_lines=False, encoding='utf-8-sig')
d = df.set_index('msg')['reply'].to_dict()
try:
input_field = driver.find_element_by_class_name("_3u328")
try:
x = next(v for k, v in d.items() if last_msg() in k)
except StopIteration:
x = 'Não entendi, este comando é invalido'
input_field.send_keys(x)
time.sleep(1)
driver.find_element_by_class_name("_3M-N-").click()
try:
driver.find_element_by_class_name("_2zCfw").send_keys('Lonely bot')
driver.find_element_by_xpath("//span[#title = '{}']".format('Lonely bot')).click()
driver.find_element_by_class_name("_2heX1").click()
WebDriverWait(driver, 600).until(EC.invisibility_of_element_located((By.NAME, "status-time")))
except TimeoutException:
loop()
except NoSuchElementException:
loop()
Here i defined a loop to keep the code online
def loop:
try:
z()
time.sleep(1)
w()
y()
driver.refresh()
except TimeoutException:
loop()
This is the first read and reply.
while True:
try:
open_chatroom()
time.sleep(1)
w()
y()
driver.refresh()
except TimeoutException:
loop()
I never experienced this before. How can i change my code so my loop doesnt break with this error?
At your exception handler, your function loop calls itself. every TimeoutException exception you creating a new stack frame, and I guess these stack frames are never emptied, eventually causing a RecursionError.
Looking at the last few items in the traceback, it seems that loop and last_msg are calling each other repeatedly, so the there is a recursion that involves two routines instead of just one calling itself. There's also a similar possible cycle through the functions loop and conversation.
The goal is to keep the chatbot running in a loop all the time, even if you hit an error of some kind, but the problem arises when loop gets called again in the exception handlers. It starts another copy of loop inside last_msg while the first copy of loop is still running. So last_msg calls loop and that in turn calls last_msg again, and none of the calls ever finish, they just pile up until you run ouf of space.
The way to solve this is to just return from the function where you catch the exception, and to replace the loop function with a while True: loop (just like the last code block in the original question).
Catching the exceptions prevents them from stopping the while loop. If something does fail then the while loop will keep trying again forever, but then it's doing it forever inside one function call, rather than a new recursive call.

An integer is required

I'm new in Python 3. I use aiohttp module for Python 3.5.
When I run my project, I have a following error
TypeError: an integer is required (got type str)
The stack-trace is:
Traceback (most recent call last):
File "/home/santi/tesis/tanner/server.py", line 82, in <module>
srv = loop.run_until_complete(f)
File "/usr/lib/python3.5/asyncio/base_events.py", line 373, in run_until_complete
return future.result()
File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
raise self._exception
File "/usr/lib/python3.5/asyncio/tasks.py", line 240, in _step
result = coro.send(None)
File "/usr/lib/python3.5/asyncio/base_events.py", line 949, in create_server
sock.bind(sa)
The code is:
if __name__ == '__main__':
loop = asyncio.get_event_loop()
f = loop.create_server(
lambda: HttpRequestHandler(debug=False, keep_alive=75),'0.0.0.0','8090')
srv = loop.run_until_complete(f)
print('serving on', srv.sockets[0].getsockname())
try:
loop.run_forever()
except KeyboardInterrupt:
pass
What is the error in my code?
What am I doing wrong?
The port number should be an Integer:
f = loop.create_server(
lambda: HttpRequestHandler(debug=False, keep_alive=75), '0.0.0.0', 8090)

Categories