Skip to content

Commit ea87b14

Browse files
committed
Merge pull request #47 from halfcrazy/handle-timeout
handle timeout request, avoid heroku 503 error
2 parents 7573a65 + 1592692 commit ea87b14

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

slack_bot/app.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import settings
1111
import plugins
1212
from ext import redis_store, cache
13+
from utils import timeout
1314
from plugins.utils import convert2str, replaced
1415

1516

@@ -40,6 +41,7 @@ def create_app(config=None):
4041
return app
4142

4243

44+
@timeout(30.0)
4345
def callback(kwargs, app):
4446
s = convert2str(kwargs['text'])
4547
trigger_word = convert2str(kwargs['trigger_word'])

slack_bot/utils.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
from multiprocessing import TimeoutError
4+
from multiprocessing.pool import ThreadPool
5+
from functools import wraps
6+
7+
8+
def timeout(seconds):
9+
def decorator(fn):
10+
@wraps(fn)
11+
def wrapper(*args, **kwargs):
12+
pool = ThreadPool(processes=1)
13+
async_result = pool.apply_async(fn, args=args, kwds=kwargs)
14+
try:
15+
return async_result.get(seconds)
16+
except TimeoutError:
17+
return kwargs.pop('default', {'text': 'timeout'})
18+
return wrapper
19+
return decorator

0 commit comments

Comments
 (0)