Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Python import
- import time
- from datetime import datetime
- # Functions
- # Python imports
- import time
- import string
- import hashlib
- #Package import
- from pymemcache import serde
- from pymemcache.client import base as base_memcache
- # Constants:
- zconsts_TIMES = 100
- zconsts_FAKE_DELAY = 5
- # Functions definition
- def fetch_from_db(key):
- # In this function we will simulate a slow database query
- time.sleep(zconsts_FAKE_DELAY)
- # Return hashed key
- return str(hashlib.md5(key.encode("utf-8")))
- def get_cache_client():
- return base_memcache.Client("10.82.1.3:11211", serde=serde.pickle_serde)
- def get_cached_object(CacheClient, key):
- message = CacheClient.get(key, None)
- if not message:
- # we dont have it on cache, we will have to look for it to Database:
- message = fetch_from_db(key)
- # After fetching we store it on cache:
- CacheClient.set(key, message)
- # At this point we have the message
- return message
- #Launch!
- if __name__ == "__main__":
- key = "Testing"
- # Instance MemCache client for every cert_sender process
- CacheClient = get_cache_client() # This could be in a lot of places of a project
- CacheClient.delete(key) # To avoid already existing key
- # Run testing
- performance = {}
- for x in range(zconsts_TIMES):
- check_time = datetime.now()
- get_cached_object(CacheClient, key) # We fetch our item
- performance[x] = (datetime.now() - check_time).total_seconds()
- # Show some results
- print("Results:")
- print(f"First time took {performance[0]:.4f}s fetching from database")
- print("At this point we set the key on Cache to retrieve value from there\n")
- print(f"All the next {zconsts_TIMES-1} fetchs should be faster")
- for idx in range(1, zconsts_TIMES):
- print(f"{idx} time\t Took {performance[idx]:.4f}s fetching from Cache")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement