Redis
This extension provides support for connecting to Redis servers. It registers the
redis.asyncio.Redis service.
Usage
First install the redis extra:
Define the configuration properties:
Inject the Redis service:
from typing import Annotated
from redis.asyncio import Redis
from selva.di import service, Inject
@service
class MyService:
# default service
redis: Annotated[Redis, Inject]
# named service
other_redis: Annotated[Redis, Inject(name="other")]
Redis connections can also be defined with username and password separated from the url, or even with individual components:
Using environment variables
data:
redis:
default:
url: "${REDIS_URL}" # (1)
other: # (2)
url: "${REDIS_URL}"
username: "${REDIS_USERNAME}"
password: "${REDIS_PASSWORD}"
another: # (3)
host: "${REDIS_HOST}"
port: ${REDIS_PORT}
db: "${REDIS_DB}"
username: "${REDIS_USERNAME}"
password: "${REDIS_PASSWORD}"
- Can be define with just the environment variable
SELVA__DATA__REDIS__DEFAULT__URL - Can be defined with just the environment variables:
SELVA__DATA__REDIS__OTHER__URLSELVA__DATA__REDIS__OTHER__USERNAMESELVA__DATA__REDIS__OTHER__PASSWORD
- Can be defined with just the environment variables:
SELVA__DATA__REDIS__ANOTHER__HOSTSELVA__DATA__REDIS__ANOTHER__PORTSELVA__DATA__REDIS__ANOTHER__DBSELVA__DATA__REDIS__ANOTHER__USERNAMESELVA__DATA__REDIS__ANOTHER__PASSWORD
Example
from typing import Annotated
from redis.asyncio import Redis
from asgikit.responses import respond_json
from selva.di import Inject
from selva.web import get
@get
async def index(request, redis: Annotated[Redis, Inject]):
number = await redis.incr("number")
await respond_json(request.response, {"number": number})
Configuration options
Selva offers several options to configure Redis. If you need more control over
the Redis service, you can create your own redis.asyncio.Redis service.
The available options are shown below:
data:
redis:
default:
url: ""
host: ""
port: 6379
db: 0
username: ""
password: ""
options: # (1)
socket_timeout: 1.0
socket_connect_timeout: 1.0
socket_keepalive: false
socket_keepalive_options:
TCP_KEEPIDLE: 100,
TCP_KEEPCNT: 100,
TCP_KEEPINTVL: 100,
unix_socket_path: ""
encoding: ""
encoding_errors: "strict" # or "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:
retries: 1
supported_errors: # (2)
- package.module.Class
backoff: # (3)
no_backoff:
constant:
backoff: 1
exponential:
cap: 1
base: 1
full_jitter:
cap: 1
base: 1
equal_jitter:
cap: 1
base: 1
decorrelated_jitter:
cap: 1
base: 1
optionsvalues are described inredis.asyncio.Redis.- Dotted path to python classes.
- Only one option in
backoffshould be set.