Created
February 1, 2018 01:53
-
-
Save capsulecorplab/e2acf22174f5a7cea07f28b7afef6134 to your computer and use it in GitHub Desktop.
Try with Timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#code gist, courtesy of Jabba Laci | |
#sauce: https://pythonadventures.wordpress.com/2012/12/08/raise-a-timeout-exception-after-x-seconds/ | |
import signal | |
import time | |
def test_request(arg=None): | |
"""Your http request.""" | |
time.sleep(2) | |
return arg | |
class Timeout(): | |
"""Timeout class using ALARM signal.""" | |
class Timeout(Exception): | |
pass | |
def __init__(self, sec): | |
self.sec = sec | |
def __enter__(self): | |
signal.signal(signal.SIGALRM, self.raise_timeout) | |
signal.alarm(self.sec) | |
def __exit__(self, *args): | |
signal.alarm(0) # disable alarm | |
def raise_timeout(self, *args): | |
raise Timeout.Timeout() | |
def main(): | |
# Run block of code with timeouts | |
try: | |
with Timeout(3): | |
print(test_request("Request 1")) | |
with Timeout(1): | |
print(test_request("Request 2")) | |
except Timeout.Timeout: | |
print("Timeout") | |
############################################################################# | |
if __name__ == "__main__": | |
main() |
@tnajun sorry for the late reply. Unfortunately, I'm not familiar with the Django framework, so I probably don't quite have enough context to understand your problem. Though, based on the error alone, it seems you're passing the correct data type, just not the correct value. Let me know if you ever managed to resolve your issue!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use your code to hit a API on Django, in order to pass if I do not get a response within one second or so. And I got the following error:
ERROR MESSAGE: <type 'exceptions.ValueError'>
signal only works in main thread
Do you have any idea?