In my work, from time to time, I have a desire to change the behavior of this or that tool: to make working with it more familiar, the API is more transparent, etc. So it happened and when I inherited a project where Redis was used as a repository. Undoubtedly, Python has enough libraries for convenient work with Redis, but remembering that this is a key-value store, I could not help but think about how wonderful it would be to work with it as with an ordinary Python dictionary (dict) .
Instead
>>> redis_obj.exist(key)
use
>>> key in redis_obj
Keep objects as usual assignments:
>>> redis_obj['Planets'] = ['Mercury', 'Venus', 'Earth', 'Mars']
This is how the dictator was born. Dictator imitates dict class methods, hiding the Redis interface from the user.
Installation is extremely simple, like many Python libraries, it is available in Pypi
$ pip install dictator
Source codes with the MIT license are taken to the repository on GitHub.
Using Dictator is extremely simple, but initializing objects is still different from the dictionary (you need to know where to connect):
>>> dc = Dictator(host='localhost', port=6379, db=0)
Then you can work with the created object in a familiar manner:
.set(key, value)
>>> dc.set('Planets', ['Mercury', 'Venus', 'Earth']) >>> dc['Stars'] = ['Sun']
.get(key)
>>> dc['Stars'] ['Sun'] >>> dc.get('Planets') ['Mercury', 'Venus', 'Earth']
You can set a value in case the key key
nothing found
>>> dc.get('Comets', 'No data') 'No data'
.update(other=None, **kwargs)
>>> dc.update({'Stars': ['Sun', 'Vega']}) >>> dc.update(Stars=['Sun'])
.pop(key, default=None)
>>> dc.pop('Stars') ['Sun'] >>> dc.pop('Comets')
.delete(key)
>>> dc.delete('Comets')
or
>>> del dc['Comets']
.keys()
and .values()
>>> dc.keys() ['Planets', 'Stars'] >>> dc.values() [['Mercury', 'Venus', 'Earth']]
.items()
>>> dc.iterms() [('Planets', ['Mercury', 'Venus', 'Earth'])]
and, of course, iteration using a generator object:
.iterkeys()
.itervalues()
.iteritems()
And that's not it :)
The project is in the initial stage, carefully documented and decorated.
Forks, pull-requests and other issues are welcome!
GitHub: dictator
Source: https://habr.com/ru/post/311820/
All Articles