Skip to main content

Serverless Redis SDK from Upstash

Project description

Upstash Redis Python SDK

[!NOTE]
This project is in GA Stage.

The Upstash Professional Support fully covers this project. It receives regular updates, and bug fixes. The Upstash team is committed to maintaining and improving its functionality.

upstash-redis is a connectionless, HTTP-based Redis client for Python, designed to be used in serverless and serverful environments such as:

  • AWS Lambda
  • Vercel Serverless
  • Google Cloud Functions
  • and other environments where HTTP is preferred over TCP.

Inspired by other Redis clients like @upstash/redis and redis-py, the goal of this SDK is to provide a simple way to use Redis over the Upstash REST API.

The SDK is currently compatible with Python 3.8 and above.

Quick Start

Install

PyPI

pip install upstash-redis

Usage

To be able to use upstash-redis, you need to create a database on Upstash and grab UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN from the console.

# for sync client
from upstash_redis import Redis

redis = Redis(url="UPSTASH_REDIS_REST_URL", token="UPSTASH_REDIS_REST_TOKEN")

# for async client
from upstash_redis.asyncio import Redis

redis = Redis(url="UPSTASH_REDIS_REST_URL", token="UPSTASH_REDIS_REST_TOKEN")

Or, if you want to automatically load the credentials from the environment:

# for sync use
from upstash_redis import Redis
redis = Redis.from_env()

# for async use
from upstash_redis.asyncio import Redis
redis = Redis.from_env()

If you are in a serverless environment that allows it, it's recommended to initialise the client outside the request handler to be reused while your function is still hot.

Running commands might look like this:

from upstash_redis import Redis

redis = Redis.from_env()

def main():
  redis.set("a", "b")
  print(redis.get("a"))

# or for async context:

from upstash_redis.asyncio import Redis

redis = Redis.from_env()

async def main():  
  await redis.set("a", "b")
  print(await redis.get("a"))

BITFIELD and BITFIELD_RO

One particular case is represented by these two chained commands, which are available as functions that return an instance of the BITFIELD and, respectively, BITFIELD_RO classes. Use the execute function to run the commands.

redis.bitfield("test_key") \
  .incrby(encoding="i8", offset=100, increment=100) \
  .overflow("SAT") \
  .incrby(encoding="i8", offset=100, increment=100) \
  .execute()

redis.bitfield_ro("test_key_2") \
  .get(encoding="u8", offset=0) \
  .get(encoding="u8", offset="#1") \
  .execute()

Custom commands

If you want to run a command that hasn't been implemented, you can use the execute function of your client instance and pass the command as a list.

redis.execute(command=["XLEN", "test_stream"])

Pipelines & Transactions

If you want to submit commands in batches to reduce the number of roundtrips, you can utilize pipelining or transactions. The difference between pipelines and transactions is that transactions are atomic: no other command is executed during that transaction. In pipelines there is no such guarantee.

To use a pipeline, simply call the pipeline method:

pipeline = redis.pipeline()

pipeline.set("foo", 1)
pipeline.incr("foo")
pipeline.get("foo")

result = pipeline.exec()

print(result)
# prints [True, 2, '2']

For transaction, use mutli:

pipeline = redis.multi()

pipeline.set("foo", 1)
pipeline.incr("foo")
pipeline.get("foo")

result = pipeline.exec()

print(result)
# prints [True, 2, '2']

You can also chain the commands:

pipeline = redis.pipeline()

pipeline.set("foo", 1).incr("foo").get("foo")
result = pipeline.exec()

print(result)
# prints [True, 2, '2']

Encoding

Although Redis can store invalid JSON data, there might be problems with the deserialization. To avoid this, the Upstash REST proxy is capable of encoding the data as base64 on the server and then sending it to the client to be decoded.

For very large data, this can add a few milliseconds in latency. So, if you're sure that your data is valid JSON, you can set rest_encoding to None.

Retry mechanism

upstash-redis has a fallback mechanism in case of network or API issues. By default, if a request fails it'll retry once, 3 seconds after the error. If you want to customize that, set rest_retries and rest_retry_interval (in seconds).

Contributing

Preparing the environment

This project uses Poetry for packaging and dependency management. Make sure you are able to create the poetry shell with relevant dependencies.

You will also need a database on Upstash.

Running tests

To run all the tests, make sure the poetry virtual environment activated with all the necessary dependencies. Set the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN environment variables and run:

poetry run pytest

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

upstash_redis-1.2.0.tar.gz (32.9 kB view details)

Uploaded Source

Built Distribution

upstash_redis-1.2.0-py3-none-any.whl (35.4 kB view details)

Uploaded Python 3

File details

Details for the file upstash_redis-1.2.0.tar.gz.

File metadata

  • Download URL: upstash_redis-1.2.0.tar.gz
  • Upload date:
  • Size: 32.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.8.18 Linux/6.5.0-1025-azure

File hashes

Hashes for upstash_redis-1.2.0.tar.gz
Algorithm Hash digest
SHA256 8708ef56241832df1ed0dd3c27c19c14ca38dc34df9c5d3fc2c1ba8c2586edc6
MD5 4cb1d492b2a87bf7267201538c9de23e
BLAKE2b-256 deec4d137a714a3e1a621fbf39eac88489291bbc43912f9c2f8f4c8258eda5be

See more details on using hashes here.

File details

Details for the file upstash_redis-1.2.0-py3-none-any.whl.

File metadata

  • Download URL: upstash_redis-1.2.0-py3-none-any.whl
  • Upload date:
  • Size: 35.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.8.18 Linux/6.5.0-1025-azure

File hashes

Hashes for upstash_redis-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a23db26bafb3706e80dbdcbdbb50bb419ca229247cb47eebfff986c59cfcaabf
MD5 7a55acbee71643734bc2d9be54fe6828
BLAKE2b-256 c5972eaef1e7ffcf846733256aba60cee69ffc86daeaf039877eae6d4ee7416c

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page