upstash-redis


Nameupstash-redis JSON
Version 1.1.0 PyPI version JSON
download
home_pagehttps://github.com/upstash/redis-python
SummaryServerless Redis SDK from Upstash
upload_time2024-05-16 08:51:33
maintainerUpstash
docs_urlNone
authorUpstash
requires_python<4.0,>=3.8
licenseMIT
keywords upstash redis serverless redis
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 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](https://github.com/upstash/upstash-redis) and [redis-py](https://github.com/redis/redis-py),
the goal of this SDK is to provide a simple way to use Redis over the [Upstash REST API](https://docs.upstash.com/redis/features/restapi).

The SDK is currently compatible with Python 3.8 and above.

<!-- toc -->

- [Upstash Redis Python SDK](#upstash-redis-python-sdk)
- [Quick Start](#quick-start)
  - [Install](#install)
    - [PyPI](#pypi)
  - [Usage](#usage)
    - [BITFIELD and BITFIELD\_RO](#bitfield-and-bitfield_ro)
    - [Custom commands](#custom-commands)
- [Encoding](#encoding)
- [Retry mechanism](#retry-mechanism)
- [Contributing](#contributing)
  - [Preparing the environment](#preparing-the-environment)
  - [Running tests](#running-tests)

<!-- tocstop -->

# Quick Start

## Install

### PyPI
```bash
pip install upstash-redis
```

## Usage
To be able to use upstash-redis, you need to create a database on [Upstash](https://console.upstash.com/)
and grab `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` from the console.

```python
# 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:

```python
# 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:

```python
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.

```python
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`.

```python
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:

```python
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`:

```python
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:

```python
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](https://python-poetry.org) 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](https://console.upstash.com/).

## 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:

```bash
poetry run pytest
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/upstash/redis-python",
    "name": "upstash-redis",
    "maintainer": "Upstash",
    "docs_url": null,
    "requires_python": "<4.0,>=3.8",
    "maintainer_email": "support@upstash.com",
    "keywords": "Upstash Redis, Serverless Redis",
    "author": "Upstash",
    "author_email": "support@upstash.com",
    "download_url": "https://files.pythonhosted.org/packages/82/cf/5785e45c08fd57b7810fad60f3681fcc377cdaa7eaef9d6811d43710a824/upstash_redis-1.1.0.tar.gz",
    "platform": null,
    "description": "# Upstash Redis Python SDK\n\n> [!NOTE]  \n> **This project is in GA Stage.**\n>\n> 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.\n\nupstash-redis is a connectionless, HTTP-based Redis client for Python, designed to be used in serverless and serverful environments such as:\n- AWS Lambda\n- Vercel Serverless\n- Google Cloud Functions\n- and other environments where HTTP is preferred over TCP.\n\nInspired by other Redis clients like [@upstash/redis](https://github.com/upstash/upstash-redis) and [redis-py](https://github.com/redis/redis-py),\nthe goal of this SDK is to provide a simple way to use Redis over the [Upstash REST API](https://docs.upstash.com/redis/features/restapi).\n\nThe SDK is currently compatible with Python 3.8 and above.\n\n<!-- toc -->\n\n- [Upstash Redis Python SDK](#upstash-redis-python-sdk)\n- [Quick Start](#quick-start)\n  - [Install](#install)\n    - [PyPI](#pypi)\n  - [Usage](#usage)\n    - [BITFIELD and BITFIELD\\_RO](#bitfield-and-bitfield_ro)\n    - [Custom commands](#custom-commands)\n- [Encoding](#encoding)\n- [Retry mechanism](#retry-mechanism)\n- [Contributing](#contributing)\n  - [Preparing the environment](#preparing-the-environment)\n  - [Running tests](#running-tests)\n\n<!-- tocstop -->\n\n# Quick Start\n\n## Install\n\n### PyPI\n```bash\npip install upstash-redis\n```\n\n## Usage\nTo be able to use upstash-redis, you need to create a database on [Upstash](https://console.upstash.com/)\nand grab `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` from the console.\n\n```python\n# for sync client\nfrom upstash_redis import Redis\n\nredis = Redis(url=\"UPSTASH_REDIS_REST_URL\", token=\"UPSTASH_REDIS_REST_TOKEN\")\n\n# for async client\nfrom upstash_redis.asyncio import Redis\n\nredis = Redis(url=\"UPSTASH_REDIS_REST_URL\", token=\"UPSTASH_REDIS_REST_TOKEN\")\n```\n\nOr, if you want to automatically load the credentials from the environment:\n\n```python\n# for sync use\nfrom upstash_redis import Redis\nredis = Redis.from_env()\n\n# for async use\nfrom upstash_redis.asyncio import Redis\nredis = Redis.from_env()\n```\n\nIf you are in a serverless environment that allows it, it's recommended to initialise the client outside the request handler\nto be reused while your function is still hot.\n\nRunning commands might look like this:\n\n```python\nfrom upstash_redis import Redis\n\nredis = Redis.from_env()\n\ndef main():\n  redis.set(\"a\", \"b\")\n  print(redis.get(\"a\"))\n\n# or for async context:\n\nfrom upstash_redis.asyncio import Redis\n\nredis = Redis.from_env()\n\nasync def main():  \n  await redis.set(\"a\", \"b\")\n  print(await redis.get(\"a\"))\n```\n\n### BITFIELD and BITFIELD_RO\nOne particular case is represented by these two chained commands, which are available as functions that return an instance of \nthe `BITFIELD` and, respectively, `BITFIELD_RO` classes. Use the `execute` function to run the commands.\n\n```python\nredis.bitfield(\"test_key\") \\\n  .incrby(encoding=\"i8\", offset=100, increment=100) \\\n  .overflow(\"SAT\") \\\n  .incrby(encoding=\"i8\", offset=100, increment=100) \\\n  .execute()\n\nredis.bitfield_ro(\"test_key_2\") \\\n  .get(encoding=\"u8\", offset=0) \\\n  .get(encoding=\"u8\", offset=\"#1\") \\\n  .execute()\n```\n\n### Custom commands\nIf you want to run a command that hasn't been implemented, you can use the `execute` function of your client instance\nand pass the command as a `list`.\n\n```python\nredis.execute(command=[\"XLEN\", \"test_stream\"])\n```\n\n### Pipelines & Transactions\n\nIf you want to submit commands in batches to reduce the number of roundtrips, you can utilize pipelining or\ntransactions. The difference between pipelines and transactions is that transactions are atomic: no other\ncommand is executed during that transaction. In pipelines there is no such guarantee.\n\nTo use a pipeline, simply call the `pipeline` method:\n\n```python\npipeline = redis.pipeline()\n\npipeline.set(\"foo\", 1)\npipeline.incr(\"foo\")\npipeline.get(\"foo\")\n\nresult = pipeline.exec()\n\nprint(result)\n# prints [True, 2, '2']\n```\n\nFor transaction, use `mutli`:\n\n```python\npipeline = redis.multi()\n\npipeline.set(\"foo\", 1)\npipeline.incr(\"foo\")\npipeline.get(\"foo\")\n\nresult = pipeline.exec()\n\nprint(result)\n# prints [True, 2, '2']\n```\n\nYou can also chain the commands:\n\n```python\npipeline = redis.pipeline()\n\npipeline.set(\"foo\", 1).incr(\"foo\").get(\"foo\")\nresult = pipeline.exec()\n\nprint(result)\n# prints [True, 2, '2']\n```\n\n# Encoding\nAlthough Redis can store invalid JSON data, there might be problems with the deserialization.\nTo 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\ndecoded. \n\nFor 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\n`rest_encoding` to `None`.\n\n# Retry mechanism\nupstash-redis has a fallback mechanism in case of network or API issues. By default, if a request fails it'll retry once, 3 seconds \nafter the error. If you want to customize that, set `rest_retries` and `rest_retry_interval` (in seconds).\n\n# Contributing\n\n## Preparing the environment\nThis project uses [Poetry](https://python-poetry.org) for packaging and dependency management. Make sure you are able to create the poetry shell with relevant dependencies.\n\nYou will also need a database on [Upstash](https://console.upstash.com/).\n\n## Running tests\nTo run all the tests, make sure the poetry virtual environment activated with all \nthe necessary dependencies. Set the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables and run:\n\n```bash\npoetry run pytest\n```\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Serverless Redis SDK from Upstash",
    "version": "1.1.0",
    "project_urls": {
        "Homepage": "https://github.com/upstash/redis-python",
        "Repository": "https://github.com/upstash/redis-python"
    },
    "split_keywords": [
        "upstash redis",
        " serverless redis"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "47a1555f7915283689604ddbc1d4151ff10c9898bbe5fadfce03d205309c9936",
                "md5": "99e5c8927e51ba57d6c2b6f2026e7434",
                "sha256": "c4ac7f474935aaebc8792adf94a2100b19c5e5625a52f1611b003451d3606d1e"
            },
            "downloads": -1,
            "filename": "upstash_redis-1.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "99e5c8927e51ba57d6c2b6f2026e7434",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.8",
            "size": 34489,
            "upload_time": "2024-05-16T08:51:31",
            "upload_time_iso_8601": "2024-05-16T08:51:31.742313Z",
            "url": "https://files.pythonhosted.org/packages/47/a1/555f7915283689604ddbc1d4151ff10c9898bbe5fadfce03d205309c9936/upstash_redis-1.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "82cf5785e45c08fd57b7810fad60f3681fcc377cdaa7eaef9d6811d43710a824",
                "md5": "8b33b3e5c89f00ab0146ed87a22fb579",
                "sha256": "e0953491546293a1218eb10c4b18cd119c8b7083435898cf55ee1b5a31c81b21"
            },
            "downloads": -1,
            "filename": "upstash_redis-1.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "8b33b3e5c89f00ab0146ed87a22fb579",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.8",
            "size": 32342,
            "upload_time": "2024-05-16T08:51:33",
            "upload_time_iso_8601": "2024-05-16T08:51:33.057979Z",
            "url": "https://files.pythonhosted.org/packages/82/cf/5785e45c08fd57b7810fad60f3681fcc377cdaa7eaef9d6811d43710a824/upstash_redis-1.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-05-16 08:51:33",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "upstash",
    "github_project": "redis-python",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "upstash-redis"
}
        
Elapsed time: 0.27619s