# upstash-redis for Python: sync, async, and serverless setup
## Install and connect
pip install upstash-redis
from upstash_redis import Redis
redis = Redis.from_env()
from_env reads UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN from
your environment. For async code:
from upstash_redis.asyncio import Redis
redis = Redis.from_env()
## Serverless: init outside the handler
If your platform allows it, create the client at module level so warm
function instances reuse it:
from upstash_redis import Redis
redis = Redis.from_env()
def handler(event, context):
redis.incr("hits")
return {"ok": True}
## Retries
The client retries once, 3 seconds after a failure, on network or API
issues. Customize with:
redis = Redis.from_env(rest_retries=3, rest_retry_interval=1)
The interval is in seconds.
## Encoding
The REST proxy can base64-encode responses server side when values are
not valid JSON. For large payloads this adds a few milliseconds, so if
you know your data is valid JSON you can set rest_encoding to None.
## Batching
Use pipeline() to batch independent commands into fewer round trips, or
multi() when you need atomicity:
pipe = redis.pipeline()
pipe.set("foo", 1)
pipe.incr("foo")
result = pipe.exec()
Commands chain too: redis.pipeline().set("a", 1).incr("a").exec().