Saravanan666/pypi-org huggingface dataset:
Package: redisbox
Redis Box---------Redis Box helps starting and stopping a sandboxed Redis instancefrom within a Python process. The Redis instance is run with atemporary directory to store any files and is configured tobe as lightweight as possible. It will choose a free port on localhost,so it will not interfere with default Redis processes.It is primarily expected to be used in unit tests and for prototyping concepts.A typical use of a Redis Box:```pythonfrom redisbox import RedisBoxbox = RedisBox()box.start()client = box.client() # redis clientassert client.ping()# do stuff with Redisbox.stop()client.ping()  # Raises error```Nose----Redis Box comes with a Nose plugin which is automatically installed.If used as a plugin, port of the running instance will be exportedin environment variable `REDISBOX_PORT`. This name can be overriddenin settings.The plugin exposes several configuration options. To see them, run:nosetests --helpThe options you are interested in start with `--redisbox-`.Unit tests----------For an easy unit tests integration there is a `RedisTestCase` classinherited from `unittest.TestCase`. It assumes tests are run from `nosetests`with `--with-redisbox` flag. `RedisTestCases` provides a `redis` clientconnected to the sandboxed redis instance and a `purge_database` helperto clean up the database after every test:```pythonfrom redisbox.unittest import RedisTestCaseclass MyTest(RedisTestCase):def setUp(self):deploy_fixtures(self.redis_client)def tearDown(self):self.purge_database()```Installation------------Get it from PyPi:pip install redisboxGet it from GitHub:pip install https://github.com/ziadsawalha/redisbox.gitAuthors=======Ziad SawalhaThanks------RedisBox is based on mongobox by Roman Kalyakin.For a list of contributors see `AUTHORS.md`.
Package: redis-bulk-cleaner
redis-bulk-cleanerDeletes keys fromRedisdatabase in bulk.FeaturesBuilt for very large scale databases (10Gb+, 100 000 000+ keys)Uses SCAN operation so it is safe to run it without downtimeCould process multiple patterns using only one SCAN operationHas option to search for given patterns, but not delete themUsageInstall it viaPyPipip install redis_bulk_cleanerFirstly check what are you going to delete with--dry-runoption:$ redis_bulk_cleaner 'test:unsubscribe_token:*' 'test:session:*' --dry-run
Search for keys:
test:unsubscribe_token:*, test:session:*
===========
test:unsubscribe_token:NDCivQ45KQcTghpS
test:session:NDCivQ45KQcTghpS
test:unsubscribe_token:9SBQ1YsDPuTETWBS
test:unsubscribe_token:MckwaZGER1GiVjoX
test:session:9SBQ1YsDPuTETWBS
test:session:MckwaZGER1GiVjoXYou could pass as many patterns as you want. Only overhead will be Regex matching slowdown.Then to actually delete keys run it without--dry-runoption:$ redis_bulk_cleaner 'test:unsubscribe_token:*' 'test:session:*'
This tools will delete ANY key that matches any of the following pattern:
test:unsubscribe_token:*, test:session:*
Do you want to continue? (y, n): y
...
6 keys cleanedBe ware: it uses regex matching sotest*will also matchtest_other:key.
However any special symbols like.?will be escaped.Note: because of SCAN behaviour it is not possible to calculate accurate estimate/percentage.
Progress bar could go beyond 100%.-D,--dry-run- Do not delete keys just print themDefault: disabled-r,--use-regex- By default patterns are redis-patterns (*equals any characters sequence including:).
If this flag is enabled then it will parse patterns as python regex expressions (some escaping may still be needed base on your shell type)Default: disabled-s,--sleep- (milliseconds) Sleep between DELETE commands to prevent high memory and cpu usage. Disabled by default.-h,--host- Redis server hostDefault:localhost-p,--port- Redis server portDefault:6379--db- Redis server dbDefault:0-P,--password- Redis server passwordDefault: No password-b, '--batch' - Redis SCAN batch sizeToo small value will cause slowdown, too high value could lead to memory issues/timeoutsDefault:500--disable-cursor-backupsBy default current scan position is saving to temporary redis variable (redis_cleaner:cursor)
so it will continue from same place after restart (in case of crash/network issues/etc)Default: EnabledAlso seeredis_bulk_cleaner --helpCreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.Free software: MIT license
Package: redis-cached
redis-cachedPython cache decorator that uses Redis or KeyDB as storage. This is very handy for replicated apps (e.g. Kubernetes), AWS Lambda functions, and other stateless apps.Features:Function result and kwarg values arepickled, so you can work with complex structures likepydantic'sBaseModelPrevents multiple simultaneous cache updates when a function is called concurrently and there is no cached value.Cache invalidation is availableLimitations:Only async functions are supported.Only keyword arguments are supported. It will raise an error if you pass non-kwargs while calling your function.Installationpipinstallredis_cachedUsageBasic usage:importasynciofromredis_cachedimportcached,invalidate_cache@cached(5)asyncdefadd_one(x):returnx+1asyncdefmain():result=awaitadd_one(x=2)# result is cached for 5 seconds# Pass the same kwargs to this func to invalidate the cacheawaitinvalidate_cache('add_one',x=2)asyncio.run(main())Optionally, add salt to the decorator to avoid clashing with the same-named functions in other modules or other apps that use the same Redis or KeyDB database:importasynciofromredis_cachedimportcached,invalidate_cacheCACHE_SALT='XnsJ-7C9PIU0qhDwh9YhJQ'@cached(5,cache_key_salt=CACHE_SALT)asyncdefadd_one(x):returnx+1asyncdefinvalidate_add_one(**kwargs):awaitinvalidate_cache('add_one',cache_key_salt=CACHE_SALT,**kwargs)asyncdefmain():result=awaitadd_one(x=2)# cachedawaitinvalidate_add_one(x=2)# invalidatedasyncio.run(main())ContributingContributions are welcome. Please refer tomaintenance readmefor more details.
Package: redis-cache-deco
Redis Cache DecoratorInstallationpipinstallredis-cache-decoExamplefromdatetimeimportdatetimeimportredisfromredis_cache_decoimportrcdrcd.init_redis_cache(redis.Redis(host='localhost',port=6379,db=0))@rcd.use_redis_cache(ttl=60)defmy_function(dt,array):print("My Function")return{"dt":dt,"array":array,"ret":"OK"}res=my_function(datetime(2021,1,1,1,1),[{"a":1}])print(res)rcd.cache_stats()parametersinit_redis_cache(redis_client_in,prefix_in="",debug_in=False)prefix_in: The prefix to use in redisdebug_in: Bypass the redis cache
Package: rediscache-decorator
Important Note :This repo is widely based onhttps://github.com/louisLouL/louisPyYet, for deployment purposes (esp. AWS Lambda), it relies too heavily on pandas.Quick startInstallpipinstallrediscache_decoratorInitializefromrediscache_decoratorimportCachefromredisimportStrictRedisredis=StrictRedis(decode_responses=True)cache=Cache(redis)ExamplesMake sure you have redis up and running.(https://redis.io/)Example1 : Cache string returnfromtimeimportsleepfromdatetimeimportdatetime@cache.ttl(300)defpseudo_calc():sleep(1)print("Computation in progress")returnstr(datetime.now())foriinrange(10):print(pseudo_calc())Example 3: Cache dict@cache.dict(60)defreturn_a_dict(*args,**kwargs):sleep(1)print("Computation in progress")return{"now":str(datetime.now())}foriinrange(5):print(return_a_dict())Example 4: Cache float number@cache.float(60)defreturn_a_float(*args,**kwargs):returnrandom()foriinrange(5):print(return_a_float())Delete Cache# Delete cache by function and signaturecache.delete_cache(return_a_float,2,b=3)# Delete cache by functioncache.delete_cache(return_a_float)# Delete all cachescache.delete_cache()
Package: redis-cache-tools
redis-cache-toolsIt provides simple decorators that can be added to any function to cache its return values.Requirements:redis 4.0.0Installation:pip install redis-cache-toolsUsage:from redis_cache import cache_it_json

@cache_it_json(limit=1000, expire=60 * 60 * 24)
def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)limitis the maximum number of keys,expireis the expire time in seconds.It is always recommended to specify a expire time, since by default redis-server will only remove keys with an expire time set in a event of full memory. But if you wish your keys to never expire, setexpiretoNone.Note that function arguments and result must be pickleable, since cache_it uses the pickle module.It is also possible to use redis-cache-tools as a object-oriented cache:>> from redis_cache import SimpleCache
>> c = SimpleCache(10)  # cache that has a maximum limit of 10 keys
>> c.store("foo", "bar")
>> c.get("foo")
'bar'
>> "foo" in c  # efficient membership test, time-complexity O(1)
True
>> len(c)  # efficient cardinality calculation, time-complexity O(1)
1
>> c.keys()  # returns all keys, time-complexity O(N) with N being the cache c cardinality
set(['foo'])
>> c.flush()  # flushes the cache, time-complexity O(N) with N being the cache c cardinality
>> "foo" in c
False
>> len(c)
0Check out more examples in the test_rediscache.py file.Advanced:Advanced users can customize the decorators even more by passing a SimpleCache object. For example:using env variables.

export REDIS_HOST=localhost
export REDIS_PORT=6379
export REDIS_PORT=3

my_cache = SimpleCache(limit=100, expire=60 * 60, hashkeys=True, host='localhost', port=6379, db=1, namespace='Fibonacci')
@cache_it(cache=my_cache)
def fib(n):
    # ...hashkeysparameter makes the SimpleCache to store keys in md5 hash. It isTrueby default in decorators, butFalseby default in a new SimpleCache object.host,portanddbare the same redis config params used in StrictRedis class of redis-py.
By default, thenamespaceis the name of the module from which the decorated function is called, but it can be overridden with thenamespaceparameter.
Package: redis-chatgpt
Redis ChatgptThis package is a useful tool specifically developed for effectively handling chat message history. This Python package's primary goal is to provide a reliable, efficient, and simple method to store chat logs in a Redis database.redis_chatgpt makes use of Redis, a fast, efficient, and highly scalable in-memory data structure store. By organizing and preserving the chat message history in Redis, users can retrieve message history promptly and easily with the best performance.This package is the perfect solution if you need to store and recover chat histories effortlessly from the Redis Database. With redis_chatgpt, you can streamline your chat log management tasks while becoming more productive and efficient with your resources.Getting startedpip install redis-chatgptTo build a simple data store:from redis_chatgpt.manager import RedisManager

redis_db = RedisManager(host="localhost", port=6379)Set dataredis_key = "chat_key"
chat_memory = [
    {
      "role": "system",
      "content": "Assistant is a large language model trained by OpenAI."
    },
    {
      "role": "assistant",
      "content": "Hello! How can I assist you today?"
    },
    {
      "role": "user",
      "content": "hi"
    },
]
redis_db.set_data(redis_key, chat_memory)Get datachat_history = redis_db.get_data(redis_key)Truncate history(conversation)# You can choose whether to update the Redis database or 
# not by specifying the 'overwrite' parameter (boolean).

data = redis_db.truncate_conversation(redis_key, overwrite=True)Use with FastAPI Swaggercd examples/chatbotGet yourOpenAIAPI keyhere.Copy env.example .env (set fastapi webserver workers and openai api key)cp env.example .envdocker-compose up -dcheck out :http://0.0.0.0:8012/docs
Package: redis-cli-cluster
Cluster-aware re-implementation ofredis-cli.Here’s the problem:$redis-cli-c-hnode-0setapplesauce->Redirectedtoslot[7092]locatedat172.255.0.3:6379OK$ctrl-D$redis-cli-c-hnode-0keys"*"(emptylistorset)$redis-cli-c-hnode-1keys"*"1)"apple"Wouldn’t it be great if thatkeys *worked the same was as in non-clustered
mode?$redis-cli-cluster-hnode-0setapplesauce->Redirectedtoslot[7092]locatedat172.255.0.3:6379OK$ctrl-D$redis-cli-cluster-hnode-0keys"*"1)"apple"
Package: redis-client
Redis clientSimple Redis client for python.It has been made to simplify working with Redis in python.UsageInstantiateCache(), give the Redishost,portanddb.Then you can get a cached entry withCache.get_data_from_cache()and add an entry to Redis withCache.save_data_to_cache()⚠️The data send to cache NEEDS TO BE A DICTIONARY! ⚠️Code examplefromredis_client.clientimportCachefromtimeimportsleepfromtpyingimportDict# Redis Configurationcache=Cache(redis_host="localhost",redis_port=6379,redis_db=0,log_level="INFO")defusername_expander(username:str)->Dict[str,str]:"""Example of a function that require caching."""# Key that will be use to retrieve cached data# Note that I include the parameter 'username' in the key to make sure we only cache unique value.key=f"username_expander:{username}"# Check if the data is already cachescached_data=cache.get_data_from_cache(key)# Return it if yesifcached_data:returncached_datadata={"expanded_username":f"{username}_123"}# Save data to cache with an expiration time of 12 hourscache.save_data_to_cache(key,data,expiration_in_hours=12)returndata
Package: redis-clu
# redis-cluRedis Cluster Management ToolCreate/Manage sharded+replicated redis cluster easily.# Installation```bashpip install redis-clu```# Usage##### Create cluster```bash# Sharded cluster (master-master)redis-clu create localhost:6376 localhost:6377 localhost:6378```##### Show status```bashredis-clu status localhost:6376```##### Add masters```bash# single node:redis-clu add localhost:6379(optional: --keyMigrationCount <count> ) pipelined command, default 1# multiple nodes:# recommended for dynamic scaling, it will be split cluster into subclusters# and each subcluster will be resharding simultaneously# <cluster> <masters>redis-clu add_multi localhost:6376 localhost:6381 localhost:6382(optional: --keyMigrationCount <count> ) pipelined command, default 1```##### Add slaves```bash# master-slave replication# To make redis cluster high available, all master should have at least one slave.# <master> <slave>redis-clu replicate localhost:6376 localhost:6385```##### Fix cluster```bashredis-clu fix localhost:6376# If occurs "Slot <slot> is already busy" execute with "--force 1"redis-clu fix localhost:6376 --force 1```##### Reshard cluster (Slot balancing)```bashredis-clu reshard localhost:6376(optional: --keyMigrationCount <count> ) pipelined command, default 1```##### Remove node```bash# <cluster> <node(master or slave)>redis-clu remove localhost:6376 localhost:6380(optional: --keyMigrationCount <count> ) pipelined command, default 1```##### Flush/Destroy cluster```bash# flush cluster (initialize with 0 keys):redis-clu reset localhost:6376# destroy cluster:redis-clu reset localhost:6376 --hard 1```# MonitoringAlso you can make your own basic monitoring screen using 'watch'.brew install watch (For Mac OSx)redis-clu status <cluster_node>watch -d -n 1 'redis-clu status localhost:6376'Monitoring will help you to make an action.![ScreenShot](https://raw.github.com/baranbartu/redis-clu/master/screenshot.png)
Package: rediscollectiondb
RedisCollectionDBDescriptionRedisCollectionDB is a Python library that provides an easy-to-use interface for managing collections and items within a Redis database. It allows for the addition and removal of collections and items, listing of current collections and items, and subscribes to changes in collections and items via Redis' publish/subscribe mechanism.InstallationInstall RedisCollectionDB using pip:pipinstallrediscollectiondbHow to UseFirst, ensure you have Redis running on your local machine or a server.fromrediscollectiondbimportRedisDB# Initialize the RedisDB instancedb=RedisDB(db_name='your_database_name')# Add a collectiondb.add_collection('books')# Add items to the collectiondb.add_item('books','The Great Gatsby')db.add_item('books','1984')# List collectionsprint(db.list_collections())# List items in a collectionprint(db.list_items('books'))# Remove an itemdb.remove_item('books','1984')# Remove a collectiondb.remove_collection('books')Handling Events with CallbacksYou can extend theRedisDBclass to handle item and collection changes by overriding theon_item_changedandon_collection_changedmethods. Here's an example:classMyRedisDB(RedisDB):defon_item_changed(self,action,collection,item):print(f"Custom handling for item:{item}in collection:{collection}, action:{action}")defon_collection_changed(self,action,collection):print(f"Custom handling for collection:{collection}, action:{action}")# Use the subclass with custom event handlingdb=MyRedisDB(db_name='myapp')# Now, adding or removing items and collections will trigger custom handlingdb.add_collection('movies')db.add_item('movies','Inception')ExampleThis example demonstrates adding a collection, adding items to it, and then listing and removing items and the collection, with custom event handling for changes.if__name__=='__main__':db=MyRedisDB(db_name='myapp')db.add_collection('books')db.add_item('books','The Great Gatsby')db.add_item('books','1984')print("Collections:",db.list_collections())print("Books items:",db.list_items('books'))db.remove_item('books','1984')print("Books items after removal:",db.list_items('books'))db.remove_collection('books')print("Collections after removing books:",db.list_collections())
Package: redis-collections
redis-collectionsis a Python library that provides a high-level
interface toRedis, the excellent key-value store.QuickstartInstall the library withpip installredis-collections.
Import the collections from the top-levelredis_collectionspackage.Standard collectionsThe standard collections (e.g.Dict,List,Set) behave like their
Python counterparts:>>>fromredis_collectionsimportDict,List,Set>>>D=Dict()>>>D['answer']=42>>>D['answer']42CollectionRedis typeDescriptionDictHashEmulates Python’sdictListListEmulates Python’slistSetSetEmulates Python’ssetCounterHashEmulates Python’scollections.CounterDefaultDictHashEmulates Python’scollections.defaultdictDequeListEmulates Python’scollections.dequeSyncable collectionsThe syncable collections in this package provide types whose
contents are kept in memory. When theirsyncmethod is called those
contents are written to Redis:>>>fromredis_collectionsimportSyncableDict>>>withSyncableDict()asD:...D['a']=1# No write to Redis...D['a']+=1# No read from or write to Redis>>>D['a']# D.sync() is called at the end of the with block2CollectionPython typeDescriptionSyncableDictdictSyncs to a Redis HashSyncableListlistSyncs to a Redis ListSyncableSetsetSyncs to a Redis SetSyncableCountercollections.CounterSyncs to a Redis HashSyncableDequecollections.dequeSyncs to a Redis ListSyncableDefaultDictcollections.defaultdictSyncs to a Redis HashOther collectionsTheLRUDictcollection stores recently used items in in memory.
It pushes older items to Redis:>>>fromredis_collectionsimportLRUDict>>>D=LRUDict(maxsize=2)>>>D['a']=1>>>D['b']=2>>>D['c']=2# 'a' is pushed to Redis and 'c' is stored locally>>>D['a']# 'b' is pushed to Redis and 'a' is retrieved for local storage1>>>D.sync()# All items are copied to RedisTheSortedSetCounterprovides access to the RedisSorted Settype:>>>fromredis_collectionsimportSortedSetCounter>>>ssc=SortedSetCounter([('earth',300),('mercury',100)])>>>ssc.set_score('venus',200)>>>ssc.get_score('venus')200.0>>>ssc.items()[('mercury',100.0),('venus',200.0),('earth',300.0)]DocumentationFor more information, seeredis-collections.readthedocs.ioMaintainersBo Bayles (@bbayles)Honza Javorek (@honzajavorek)License: ISC© 2016-? Bo Bayles <bbayles@gmail.com> and contributors
© 2013-2016 Honza Javorek <mail@honzajavorek.cz> and contributorsThis work is licensed underISC license.This library is not affiliated withRedis Labs,Redis, orredis-py. Govern yourself accordingly!
Package: redis-completion
autocompletion withredisbased on:http://antirez.com/post/autocomplete-with-redis.htmlhttp://stackoverflow.com/questions/1958005/redis-autocomplete/1966188http://patshaughnessy.net/2011/11/29/two-ways-of-using-redis-to-build-a-nosql-autocomplete-search-indexredis-completion is capable of storing a large number of phrases and quickly
searching them for matches.  Rich data can be stored and retrieved, helping you
avoid trips to the database when retrieving search results.check out thedocumentationfor more info.usageIf you just want to store really simple things, like strings:engine = RedisEngine()
titles = ['python programming', 'programming c', 'unit testing python',
          'testing software', 'software design']
map(engine.store, titles)

>>> engine.search('pyt')
['python programming', 'unit testing python']

>>> engine.search('test')
['testing software', 'unit testing python']If you want to store more complex data, like blog entries:Entry.create(title='an entry about python', published=True)
Entry.create(title='all about redis', published=True)
Entry.create(title='using redis with python', published=False)

for entry in Entry.select():
    engine.store_json(entry.id, entry.title, {
        'published': entry.published,
        'title': entry.title,
        'url': entry.get_absolute_url(),
    })

>>> engine.search_json('pytho')
[{'published': True, 'title': 'an entry about python', 'url': '/blog/1/'},
 {'published': False, 'title': 'using redis with python', 'url': '/blog/3/'}]

# just published entries, please
>>> engine.search_json('redis', filters=[lambda i: i['published'] == True])
[{u'published': True, u'title': u'all about redis', u'url': u'/blog/2/'}]installingInstall with pip:pip install redis-completionInstall via git:git clone https://github.com/coleifer/redis-completion.git
cd redis-completion
python setup.py installschema
Package: redisconfig
redisconfigSimple, robust Redis configuration for PythonInstallationpip install redisconfigBasic Usage>>> import redisconfig

>>> config = redisconfig.RedisConfig()
RedisConfig(host='127.0.0.1', port=6379, db=0, ssl=False, password=None)

>>> config.host
'127.0.0.1'

>>> config.url()
'redis://127.0.0.1:6379/0'

>>> config.connection()
Redis<ConnectionPool<Connection<host=127.0.0.1,port=6379,db=0>>>REDIS_URL Environment VariableIn many cases the Redis connection URL is stored in the REDIS_URL environment variable. redisconfig will use that value as a default for several operations, such as the module-level config() and connection() methods. With an environment variable ofREDIS_URL=rediss://noop:badpassword@10.0.0.1/2:>>> redisconfig.config()
RedisConfig(host='10.0.0.1', port=6379, db=2, ssl=True, password='badpassword')

>>> redisconfig.connection()
Redis<ConnectionPool<SSLConnection<host=10.0.0.1,port=6379,db=2>>>Update Configuration ValuesYou can update values directly likeconfig.db = 5but sometimes you want to change values without changing the underlying configuration. The url() and replace() methods on RedisConfig allow you to make new urls or configs without changing the original values.Create a new URL:>>> config = redisconfig.RedisConfig()
>>> config.url()
'redis://127.0.0.1:6379/0'

>>> config.url(db=2)
'redis://127.0.0.1:6379/2'Create a new RedisConfig instance:>>> config.replace(db='10.0.0.1')
RedisConfig(host='10.0.0.1', port=6379, db=0, ssl=False, password=None)DevelopingThe following things are needed to use this repository:GitPython 3.6.2+PoetryOnce you have the prerequisites installed and have cloned the repository you can ready your development environment withpoetry install -E dev. You should see output similar to:$ poetry install -E dev
Creating virtualenv redisconfig in /tmp/redisconfig/.venv
Installing dependencies from lock file

...

Installing the current project: redisconfig (0.1.1)Testingpoetry run pytestChangelog0.1.1Fix typing-extensions import on Python >=3.80.1.0Initial release
Package: redis-connector
redis_connectorRedis pub/sub connectorFree software: MIT licenseDocumentation:https://redis-connector.readthedocs.io.FeaturesTODOCreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.0.5 (2018-07-02)Implementing ping0.0.4 (2018-07-02)Implementing ping0.0.3 (2018-06-30)Implementing ping0.0.2 (2018-06-30)First release on PyPI.0.0.1 (2018-06-30)First release on PyPI.