Skip to content

Commit c252b4b

Browse files
committed
Add timeout decorator
Taken from here: https://stackoverrun.com/es/q/473410
1 parent 1c43468 commit c252b4b

1 file changed

Lines changed: 29 additions & 1 deletion

File tree

api/utils.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
# -*- coding: utf-8 -*-
33

44
import os
5+
import errno
56
import shelve
7+
import signal
8+
from functools import wraps
69
from typing import NamedTuple, List, Any
710

811
from . import constants
@@ -13,7 +16,13 @@
1316
import symbols
1417

1518

16-
__all__ = ['read_txt_file', 'open_file', 'sanitize_filename', 'flatten_list']
19+
__all__ = [
20+
'read_txt_file',
21+
'open_file',
22+
'sanitize_filename',
23+
'flatten_list',
24+
'timeout'
25+
]
1726

1827
__doc__ = """Utils module contains many helpers for several task, like reading files
1928
or path management"""
@@ -136,3 +145,22 @@ def get_final_value(symbol: symbols.SYMBOL):
136145
result = result.value
137146

138147
return result
148+
149+
150+
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
151+
def decorator(func):
152+
def _handle_timeout(signum, frame):
153+
raise TimeoutError(error_message)
154+
155+
def wrapper(*args, **kwargs):
156+
signal.signal(signal.SIGALRM, _handle_timeout)
157+
signal.alarm(seconds)
158+
try:
159+
result = func(*args, **kwargs)
160+
finally:
161+
signal.alarm(0)
162+
return result
163+
164+
return wraps(func)(wrapper)
165+
166+
return decorator

0 commit comments

Comments
 (0)