SoFunction
Updated on 2025-03-02

Python timeout request or calculation processing scheme

Timeout mechanism

Generally used to deal with blocking problems

Scene:

  • Computation with high complexity (analysis) a certain value, encrypted and decrypted calculation, etc.
  • Blockage during request, avoid waiting for a long time
  • Network fluctuations, avoid long-term requests, and waste time

1. Requests request timeout mechanism

The requests dependency has the timeout parameter in the Post request, which can be set directly

response = (url, 
						data=request_body, 
						headers=headers, 
						timeout=timeout)

2. Other function time-out mechanism

Customize a timeout function timeout()

import signal
from functools import wraps
import errno
import os
class TimeoutError(Exception):
    pass
def timeout(seconds=10, error_message=()):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)
        def wrapper(*args, **kwargs):
            (, _handle_timeout)
            (seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                (0)
            return result
        return wraps(func)(wrapper)
    return decorator
@timeout(5)
def long_running_function():
    # Here is the code that may run for a long time    # For example, you can use simulating long-running operations    import time
    (10)
try:
    long_running_function()
except TimeoutError as e:
    print("Function call timed out")

Note:

References to writing timeout() function ChatGPT4.0

This is the end of this article about the processing of Python timeout requests or calculations. For more related Python timeout requests, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!