Redis¶
This module provides support for connecting to Redis (or Valkey) servers through the Redis library.
Usage¶
First install the redis extra:
$ pip install zayt[redis]
Define the configuration properties:
settings = {
"modules": [
"zayt.ext.redis", # (1)
],
"redis": {
"": { # (2)
"url": "redis://localhost:6379/0",
},
"other": { # (3)
"url": "redis://localhost:6379/1",
},
},
}
Note
Activate the module
Connection will be registered without a name
Connection registered with name “other”
Inject the redis.asyncio.Redis service:
from typing import Annotated
from redis.asyncio import Redis
from zayt.di import service, Inject
@service
class MyService:
# default service
redis: Annotated[Redis, Inject]
# named service
other_redis: Annotated[Redis, Inject("other")]
Redis connections can also be defined with username and password separated from the url, or even with individual components:
settings = {
"redis": {
"url_username_password": { # (1)
"url": "redis://localhost:6379/0",
"username": "user",
"password": "pass",
},
"individual_components": { # (2)
"host": "localhost",
"port": 6379,
"db": 0,
"username": "user",
"password": "pass",
},
},
}
Note
Username and password separated from the redis url
Each component defined individually
Example¶
application/handler.py¶
from redis.asyncio import Redis
from zayt.web import get
@get
async def index(request, redis: Redis):
number = await redis.incr("number")
await request.respond_json({"number": number})
configuration/settings.py¶
settings = {
"redis": {
"": {
"url": "redis://localhost:6379/0",
},
},
}
Configuration options¶
The available options are shown below:
settings = {
"redis": {
"": {
"url": "",
"host": "",
"port": 6379,
"db": 0,
"username": "",
"password": "",
"options": {
"socket_timeout": 1.0,
"socket_connect_timeout": 1.0,
"socket_keepalive": False,
"socket_keepalive_options": {},
"unix_socket_path": "",
"encoding": "",
"encoding_errors": "strict", # "ignore", "replace"
"decode_responses": False,
"retry_on_timeout": False,
"retry_on_error": [],
"ssl": False,
"ssl_keyfile": "",
"ssl_certfile": "",
"ssl_cert_reqs": "",
"ssl_ca_certs": "",
"ssl_ca_data": "",
"ssl_check_hostname": False,
"max_connections": 1,
"single_connection_client": False,
"health_check_interval": 1,
"client_name": "",
"lib_name": "",
"lib_version": "",
"auto_close_connection_pool": False,
"protocol": 3,
"retry": {},
},
},
},
}
Note
options values are described in redis.asyncio.client.Redis.