Найти - Пользователи
Полная версия: Прервать выполнение requests.get().text
Начало » Python для экспертов » Прервать выполнение requests.get().text
1
Mr.Anderson
Привет всем. Столкнулся с проблемой долгой загрузки сайта, с помощью requests.get().text
Суть вопроса, как прервать выполнение функции через како либо время?
Решение типа requests.get('link', timeout.text не помогает, функция все так же пытается получить код страницы.
Как можно решить данную проблему?
JOHN_16
timeout “не работает” потому что:
Note
timeout is not a time limit on the entire response download; rather, an exception is raised if the server has not issued a response for timeout seconds (more precisely, if no bytes have been received on the underlying socket for timeout seconds). If no timeout is specified explicitly, requests do not time out.
ОС какая ?
Mr.Anderson
JOHN_16
timeout “не работает” потому что:
Ос Linux, дебиан
JOHN_16
Mr.Anderson
Это хорошо - посмотрите варианты по ссылке выше, там , на вскидку, не один вариант который вам подойдет
Mr.Anderson
Взял от туда первое решение
 import signal
# Register an handler for the timeout
def handler(signum, frame):
     print("Forever is over!")
     raise Exception("end of time")
# This function *may* run for an indetermined time...
def loop_forever():
    html_codes = requests.get('https://books.google.ru/books?isbn=3659226408').text
# Register the signal function handler
signal.signal(signal.SIGALRM, handler)
# Define a timeout for your function
signal.alarm(3)
try:
     loop_forever()
except Exception:
     print('!')

Не помогло, все равно зависает
Mr.Anderson
Вопрос закрыт, помогло это решение
 import multiprocessing.pool
import functools
def timeout(max_timeout):
    """Timeout decorator, parameter in seconds."""
    def timeout_decorator(item):
        """Wrap the original function."""
        @functools.wraps(item)
        def func_wrapper(*args, **kwargs):
            """Closure for function."""
            pool = multiprocessing.pool.ThreadPool(processes=1)
            async_result = pool.apply_async(item, args, kwargs)
            # raises a TimeoutError if execution exceeds max_timeout
            return async_result.get(max_timeout)
        return func_wrapper
    return timeout_decorator
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB