EDIT So my B class receives messages for a telegram bot, this is the code, for each message received call the function in class A
@bot.message_handler(commands=['get'])
def get(message):
uid = message.chat.id
#url that should return a 404 error
response = get_response(url)
#if I get a "get" command while the previous message received is still trying to execute the requests
#the requests do not return a 404 message as it should (I know this because I deliberately pass a link that returns an error 404)
if response.status_code == 404:
bot.send_message(uid,"404")
return
else:
#other
this is the code of the class A function
def get_response(url):
ua = UserAgent()
while (True):
for i in range(1, len(proxies)):
proxy = next(proxy_pool)
try:
header = {'User-Agent': str(ua.random)}
response = requests.get(url, headers=header, proxies={"http": proxy, "https": proxy}, verify=False,
timeout=10)
return response
except:
print("Skipping. Connnection error")
#other conditions to break the while loop
return None
This method is called by other classes B and C and by different threads, the problem is that I think the requests.get()
is not a threadsafe function and therefore does not work well when it is called by multiple threads at the same time. For example if I call requests.get()
simultaneously from multiple threads with links that should return a 404 error, this error is not returned, while it is returned if the call to requests.get()
is made individually.
So how to make this method thread safe and work properly if it is called by multiple threads?