Advertisement
DigitalMag

key manager for dict (unique key autogeneration)

Jul 4th, 2020
1,457
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. #-------------------------------------------------------------------------------
  3. # Name:        r_manager
  4. # Purpose:
  5. #
  6. # Author:      User
  7. #
  8. # Created:     03.07.2020
  9. # Copyright:   (c) User 2020
  10. # Licence:     <your licence>
  11. #-------------------------------------------------------------------------------
  12.  
  13. import itertools
  14. import time
  15. import datetime
  16.  
  17. class RequestManager:
  18.  
  19.     def __init__(self, _dct=None):
  20.         self._dict = _dct or {}
  21.         self.removed = []
  22.         self._next = (max(self._dict.keys()) + 1) if self._dict else 0
  23.  
  24.     def pop(self, key):
  25.         val = self._dict.pop(key, None)
  26.         if val: self.removed.append(key)
  27.         return val
  28.  
  29.     def append(self, values):
  30.         key = self._get_next()
  31.         self._dict[key] = values
  32.         return key
  33.  
  34.     def _get_next(self):
  35.         if len(self.removed) > 0:
  36.             key = self.removed.pop()
  37.             return key
  38.         else:
  39.             _next = self._next
  40.             self._next += 1
  41.             return _next
  42.  
  43.  
  44.     # has_key
  45.     # del
  46.  
  47.  
  48. def main():
  49.  
  50.     d = {}
  51.     for i in range(1000000): d[i]=(i+1, datetime.time)
  52.  
  53.  
  54.     t = time.clock()
  55.  
  56.     r_manager = RequestManager(d)
  57.     skey = 000001
  58.  
  59.     # (skey) # request_time, refresh_token
  60.     # skey  - секретный ключ
  61.     # дата создания (нужна для очистки неиспользуемых ключей).
  62.     r_manager.append((skey, datetime.time))
  63.  
  64.  
  65.     print(time.clock() - t)
  66.  
  67.  
  68.     t = time.clock()
  69.  
  70.     print r_manager.pop(1)
  71.  
  72.     print(time.clock() - t)
  73.  
  74. if __name__ == '__main__':
  75.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement