Skip to content

Commit a975cae

Browse files
committed
implement simple Promise for run_async/conversationhandler
1 parent 4c68a9b commit a975cae

File tree

3 files changed

+58
-5
lines changed

3 files changed

+58
-5
lines changed

telegram/ext/conversationhandler.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
from telegram import Update
2424
from telegram.ext import Handler
25+
from telegram.utils.promise import Promise
2526

2627

2728
class ConversationHandler(Handler):
@@ -111,6 +112,10 @@ def check_update(self, update):
111112
key = (chat.id, user.id) if chat else (None, user.id)
112113
state = self.conversations.get(key)
113114

115+
if isinstance(state, Promise):
116+
self.logger.debug('waiting for promise...')
117+
state = state.result()
118+
114119
self.logger.debug('selecting conversation %s with state %s' % (str(key), str(state)))
115120

116121
handler = None

telegram/ext/dispatcher.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
from telegram.utils import request
3131
from telegram.ext.handler import Handler
3232
from telegram.utils.deprecate import deprecate
33+
from telegram.utils.promise import Promise
3334

3435
logging.getLogger(__name__).addHandler(NullHandler())
3536

@@ -45,17 +46,16 @@ def _pooled():
4546
A wrapper to run a thread in a thread pool
4647
"""
4748
while 1:
48-
try:
49-
func, args, kwargs = ASYNC_QUEUE.get()
49+
promise = ASYNC_QUEUE.get()
5050

5151
# If unpacking fails, the thread pool is being closed from Updater._join_async_threads
52-
except TypeError:
52+
if not isinstance(promise, Promise):
5353
logging.getLogger(__name__).debug("Closing run_async thread %s/%d" %
5454
(current_thread().getName(), len(ASYNC_THREADS)))
5555
break
5656

5757
try:
58-
func(*args, **kwargs)
58+
promise.run()
5959

6060
except:
6161
logging.getLogger(__name__).exception("run_async function raised exception")
@@ -80,7 +80,9 @@ def async_func(*args, **kwargs):
8080
"""
8181
A wrapper to run a function in a thread
8282
"""
83-
ASYNC_QUEUE.put((func, args, kwargs))
83+
promise = Promise(func, args, kwargs)
84+
ASYNC_QUEUE.put(promise)
85+
return promise
8486

8587
return async_func
8688

telegram/utils/promise.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#!/usr/bin/env python
2+
#
3+
# A library that provides a Python interface to the Telegram Bot API
4+
# Copyright (C) 2015-2016
5+
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
6+
#
7+
# This program is free software: you can redistribute it and/or modify
8+
# it under the terms of the GNU Lesser Public License as published by
9+
# the Free Software Foundation, either version 3 of the License, or
10+
# (at your option) any later version.
11+
#
12+
# This program is distributed in the hope that it will be useful,
13+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15+
# GNU Lesser Public License for more details.
16+
#
17+
# You should have received a copy of the GNU Lesser Public License
18+
# along with this program. If not, see [http://www.gnu.org/licenses/].
19+
""" This module contains the Promise class """
20+
21+
from threading import Event
22+
23+
24+
class Promise(object):
25+
"""A simple Promise implementation for the run_async decorator"""
26+
27+
def __init__(self, pooled_function, args, kwargs):
28+
self.pooled_function = pooled_function
29+
self.args = args
30+
self.kwargs = kwargs
31+
self._done = Event()
32+
self._result = None
33+
34+
def run(self):
35+
try:
36+
self._result = self.pooled_function(*self.args, **self.kwargs)
37+
38+
except:
39+
raise
40+
41+
finally:
42+
self._done.set()
43+
44+
def result(self, timeout=None):
45+
self._done.wait(timeout=timeout)
46+
return self._result

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy