upstash-redis Python: sync and async clients, from_env, init outside the handler
Shows how to fix upstash-redis Python: sync and async clients, from_env, init outside the handler. Use it when you hit this exact problem. Skip it when your error message or symptom looks different.
TL;DR
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().
Steps
- pip install upstash-redis
- from upstash_redis import Redis
- redis = Redis.from_env()
- fromenv reads UPSTASHREDISRESTURL and UPSTASHREDISREST_TOKEN from
your environment. For async code:
- from upstash_redis.asyncio import Redis
- redis = Redis.from_env()
- 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}
- 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.
- 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().
When to use
You are seeing this: For async code: from upstashredis.asyncio import Redis redis = Redis.fromenv() Use this skill when you run into "upstash-redis Python: sync and async clients, from_env, init outside the handler".
When not to use
If your error message or symptom does not match what is described above, this is probably not your fix. Search for your exact error text instead of forcing this one to fit.
Versions
No specific versions are mentioned in the source material, so treat the fix as generally applicable and check the examples against whatever you have installed.
Why this happens
The original report does not dig into a root cause. It documents the symptom and the fix that resolved it.
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.