Make Throttle async aware (#13027)

* Make Throttle async aware

* Lint
This commit is contained in:
Paulus Schoutsen committed 2018-03-09 19:42:35 -08:00
1 parent 8f807a3006
commit 6ffc53b290
11 files changed
+54 -48

No files matched your search

+13 -2
View File
@@ -1,4 +1,5 @@
"""Helper methods for various modules."""
import asyncio
from collections.abc import MutableSet
from itertools import chain
import threading
@@ -276,6 +277,16 @@ class Throttle(object):
is_func = (not hasattr(method, '__self__') and
'.' not in method.__qualname__.split('.<locals>.')[-1])
# Make sure we return a coroutine if the method is async.
if asyncio.iscoroutinefunction(method):
async def throttled_value():
"""Stand-in function for when real func is being throttled."""
return None
else:
def throttled_value():
"""Stand-in function for when real func is being throttled."""
return None
@wraps(method)
def wrapper(*args, **kwargs):
"""Wrap that allows wrapped to be called only once per min_time.
@@ -298,7 +309,7 @@ class Throttle(object):
throttle = host._throttle[id(self)]
if not throttle[0].acquire(False):
return None
return throttled_value()
# Check if method is never called or no_throttle is given
force = kwargs.pop('no_throttle', False) or not throttle[1]
@@ -309,7 +320,7 @@ class Throttle(object):
throttle[1] = utcnow()
return result
return None
return throttled_value()
finally:
throttle[0].release()