File tree Expand file tree Collapse file tree 3 files changed +30
-9
lines changed Expand file tree Collapse file tree 3 files changed +30
-9
lines changed Original file line number Diff line number Diff line change 11# coding=utf-8
2+ import time
23import os
34import re
5+ from multiprocessing .pool import ThreadPool
46
5- from flask import Flask
7+ from flask import Flask , g
68
79from flask_slackbot import SlackBot
810
@@ -37,10 +39,23 @@ def create_app(config=None):
3739 slackbot .set_handler (callback )
3840 slackbot .filter_outgoing (_filter )
3941
42+ def _set_time ():
43+ while True :
44+ g .time = time .time ()
45+
46+ @app .before_request
47+ def start_time_it ():
48+ g .pool = ThreadPool (processes = 1 )
49+ g .pool .apply_async (_set_time )
50+
51+ @app .after_request
52+ def end_time_it ():
53+ g .pool .close ()
54+
4055 return app
4156
4257
43- @timeout (30.0 )
58+ @timeout (g , 30.0 )
4459def callback (kwargs ):
4560 s = convert2str (kwargs ['text' ])
4661 trigger_word = convert2str (kwargs ['trigger_word' ])
Original file line number Diff line number Diff line change @@ -37,7 +37,8 @@ def handle(data):
3737
3838
3939if __name__ == '__main__' :
40- from flask import Flask
41- app = Flask (__name__ )
42- app .config ['org_name' ] = 'python-cn'
43- print handle (None )
40+ # from flask import Flask
41+ # app = Flask(__name__)
42+ # app.config['org_name'] = 'python-cn'
43+ # print handle(None)
44+ pass
Original file line number Diff line number Diff line change 11#!/usr/bin/env python
22# -*- coding: utf-8 -*-
3+ import time
34from multiprocessing import TimeoutError
45from multiprocessing .pool import ThreadPool
56from functools import wraps
67
78
8- def timeout (seconds ):
9+ def timeout (g , seconds , default = "timeout" ):
910 def decorator (fn ):
1011 @wraps (fn )
1112 def wrapper (* args , ** kwargs ):
1213 pool = ThreadPool (processes = 1 )
1314 async_result = pool .apply_async (fn , args = args , kwds = kwargs )
1415 try :
15- return async_result .get (seconds )
16+ # the time cost before start fn
17+ cost_time = time .time () - g .time
18+ return async_result .get (seconds - cost_time )
1619 except TimeoutError :
17- return kwargs .pop ('default' , {'text' : 'timeout' })
20+ return default () if callable (default ) else default
21+ finally :
22+ pool .close ()
1823 return wrapper
1924 return decorator
You can’t perform that action at this time.
0 commit comments