G
G
GilbertAmethyst2018-07-06 14:38:50
Python
GilbertAmethyst, 2018-07-06 14:38:50

How to catch an error in a Python thread?

Hello.
I am writing a fairly simple application in Python (3.6).
Task:
Make multiple repetitive asynchronous get requests with digest authorization.
Currently using the following code:
For example, I deliberately made a mistake: I set the timeout to 5 seconds for a request that is guaranteed to last 10. An error occurs. I would like to handle it somehow, but I do not understand how to do it.

from threading import Thread
from requests import get, post, put, patch, delete, options, head
from requests.auth import HTTPDigestAuth

request_methods = {
    'get': get,
    'post': post,
    'put': put,
    'patch': patch,
    'delete': delete,
    'options': options,
    'head': head,
}

def result(response, otherdata):
    print(str("OtherData: ") + otherdata + str(" Content: ") + str(response.content))
    input("Job done!")

def async_request(method, *args, callback=None, timeout=15, **kwargs):
    method = request_methods[method.lower()]
    if callback:
        def callback_with_args(response, *args, **kwargs):
            callback(response)
        kwargs['hooks'] = {'response': callback_with_args}
    kwargs['timeout'] = timeout
    thread = Thread(target=method, args=args, kwargs=kwargs)
    thread.start()

async_request('get', 'http://httpbin.org/delay/10', auth=HTTPDigestAuth("login", "pass"), timeout=5, callback=lambda res: result(res,"123"))

Please tell me the code if possible.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
santaatnas, 2018-07-06
@santaatnas

I know the only way to catch an error is to include the called method in a try block and catch it in an except block.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question