Guest User

asyncdec

a guest
May 27th, 2020
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. try:
  2.     from functools import wraps
  3.     from time import sleep
  4.     import threading
  5.     from queue import Queue
  6.     import redis
  7.     import sys
  8.     import time
  9.     import asyncio
  10.     from queue import Queue
  11.     print("{}".format(sys.version))
  12. except Exception as e:
  13.     print("Failed : {} ".format(e))
  14.  
  15.  
  16. global r
  17. r = redis.Redis(host='localhost', port=6379, db=0)
  18.  
  19. queue = Queue()
  20.  
  21.  
  22.  
  23. def cache(function=None):
  24.     @wraps(function)
  25.     def wrapper(*args, **kwargs):
  26.         num = args[0]
  27.         val = r.get(str(num))
  28.         if val:
  29.             print("cached Value")
  30.             return val
  31.         else:
  32.             _ = function(*args, **kwargs)
  33.             r.set(str(num), str(_))
  34.             return _
  35.     return wrapper
  36.  
  37.  
  38. @cache
  39. def compute(num):
  40.     num = num * num
  41.     time.sleep(4)
  42.     return num * num
  43.  
  44.  
  45. def cache_async(f):
  46.     async def wrapper(*args, **kwargs):
  47.         num = args[0]
  48.         val = r.get(str(num))
  49.         if val:
  50.             print("cached Value")
  51.             queue.put(int(val))
  52.             return val
  53.         else:
  54.             _ = await f(*args, **kwargs)
  55.             r.set(str(num), str(_))
  56.             queue.put(_)
  57.             return _
  58.     return wrapper
  59.  
  60.  
  61. @cache_async
  62. async def computeSquare(num):
  63.     num = num * num
  64.     await asyncio.sleep(3)
  65.     return num
  66.  
  67.  
  68. if __name__ == "__main__":
  69.     asyncio.run(computeSquare(4343))
  70.     while True:
  71.         flag = queue.empty()
  72.         if flag:
  73.             pass
  74.         else:
  75.             tem = queue.get()
  76.             break
  77.     print("VALUE : {}".format(tem))
  78.  
  79.     # val = compute(445)
  80.     # print(val)
Add Comment
Please, Sign In to add comment