Upstash Redis Python SDK

1.7.0 · active · verified Wed Apr 15

The `upstash-redis` library is a connectionless, HTTP-based Redis client for Python, specifically designed for serverless and serverful environments where HTTP is preferred over TCP (e.g., AWS Lambda, Vercel, Google Cloud Functions). It provides a simple, Pythonic interface to interact with Upstash Redis databases via their REST API. The SDK is currently in GA stage, receives regular updates and bug fixes, and its latest stable version is 1.7.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize both synchronous and asynchronous Upstash Redis clients using environment variables (`UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`). It performs a simple `SET` and `GET` operation. In serverless environments, it is recommended to initialize the client outside the request handler to maximize reuse and efficiency. [1, 3, 8, 9]

import os
from upstash_redis import Redis

# Ensure environment variables are set for demonstration
# In a real application, set UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN
# in your environment or pass them directly to Redis().
os.environ['UPSTASH_REDIS_REST_URL'] = os.environ.get('UPSTASH_REDIS_REST_URL', 'YOUR_UPSTASH_REDIS_REST_URL')
os.environ['UPSTASH_REDIS_REST_TOKEN'] = os.environ.get('UPSTASH_REDIS_REST_TOKEN', 'YOUR_UPSTASH_REDIS_REST_TOKEN')

def run_sync_example():
    try:
        redis_sync = Redis.from_env()
        redis_sync.set('mykey_sync', 'myvalue_sync')
        value = redis_sync.get('mykey_sync')
        print(f"Sync: Set 'mykey_sync' to 'myvalue_sync', retrieved: {value}")
        redis_sync.delete('mykey_sync')
    except Exception as e:
        print(f"Sync example failed: {e}")

if __name__ == '__main__':
    print("Running synchronous example...")
    run_sync_example()

    # Async example (requires asyncio and aiohttp)
    import asyncio
    from upstash_redis.asyncio import Redis

    async def run_async_example():
        try:
            redis_async = Redis.from_env()
            await redis_async.set('mykey_async', 'myvalue_async')
            value = await redis_async.get('mykey_async')
            print(f"Async: Set 'mykey_async' to 'myvalue_async', retrieved: {value}")
            await redis_async.delete('mykey_async')
        except Exception as e:
            print(f"Async example failed: {e}")

    print("\nRunning asynchronous example...")
    asyncio.run(run_async_example())

view raw JSON →