TITLE: Basic Usage of Upstash Redis Client DESCRIPTION: This TypeScript example illustrates how to initialize the Upstash Redis client with your REST URL and token, and then perform various common Redis operations including string manipulation (SET, GET), sorted sets (ZADD, ZRANGE), lists (LPUSH, LRANGE), hashes (HSET, HGET), and sets (SADD, SPOP). SOURCE: https://upstash.com/docs/redis/sdks/ts/getstarted.mdx LANGUAGE: ts CODE: ``` import { Redis } from "@upstash/redis" const redis = new Redis({ url: , token: , }) // string await redis.set('key', 'value'); let data = await redis.get('key'); console.log(data) await redis.set('key2', 'value2', {ex: 1}); // sorted set await redis.zadd('scores', { score: 1, member: 'team1' }) data = await redis.zrange('scores', 0, 100 ) console.log(data) // list await redis.lpush('elements', 'magnesium') data = await redis.lrange('elements', 0, 100 ) console.log(data) // hash await redis.hset('people', {name: 'joe'}) data = await redis.hget('people', 'name' ) console.log(data) // sets await redis.sadd('animals', 'cat') data = await redis.spop('animals', 1) console.log(data) ``` ---------------------------------------- TITLE: Google Cloud Function: ioredis Redis Counter DESCRIPTION: This JavaScript code defines a Google Cloud Function (`helloGET`) that connects to an Upstash Redis instance using the `ioredis` client. It increments a 'counter' key in Redis with each invocation and returns the updated value as a page view count. Requires Redis connection details (endpoint, password, port). SOURCE: https://upstash.com/docs/redis/howto/getstartedgooglecloudfunctions.mdx LANGUAGE: javascript CODE: ``` var Redis = require("ioredis"); if (typeof client === "undefined") { var client = new Redis("rediss://:YOUR_PASSWORD@YOUR_ENDPOINT:YOUR_PORT"); } exports.helloGET = async (req, res) => { let count = await client.incr("counter"); res.send("Page view:" + count); }; ``` ---------------------------------------- TITLE: Express Application with Redis Session Store DESCRIPTION: This JavaScript code defines an Express.js application that utilizes 'connect-redis' to persist session data in a Redis database. It initializes a Redis client, configures the session middleware with a Redis store, and sets up routes to demonstrate session-based view counting for different paths. SOURCE: https://upstash.com/docs/redis/tutorials/express_session.mdx LANGUAGE: javascript CODE: ``` var express = require("express"); var parseurl = require("parseurl"); var session = require("express-session"); const redis = require("redis"); var RedisStore = require("connect-redis")(session); var client = redis.createClient({ // REPLACE HERE }); var app = express(); app.use( session({ store: new RedisStore({ client: client }), secret: "forest squirrel", resave: false, saveUninitialized: true, }) ); app.use(function (req, res, next) { if (!req.session.views) { req.session.views = {}; } // get the url pathname var pathname = parseurl(req).pathname; // count the views req.session.views[pathname] = (req.session.views[pathname] || 0) + 1; next(); }); app.get("/foo", function (req, res, next) { res.send("you viewed this page " + req.session.views["/foo"] + " times"); }); app.get("/bar", function (req, res, next) { res.send("you viewed this page " + req.session.views["/bar"] + " times"); }); app.listen(3000, function () { console.log("Example app listening on port 3000!"); }); ``` ---------------------------------------- TITLE: Python Examples for Redis SET Command DESCRIPTION: Illustrative Python code snippets demonstrating various ways to use the Redis `SET` command, including basic usage, conditional setting (NX/XX), setting expirations, and retrieving old values. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/string/set.mdx LANGUAGE: python CODE: ``` assert redis.set("key", "value") == True assert redis.get("key") == "value" ``` LANGUAGE: python CODE: ``` # Only set the key if it does not already exist. assert redis.set("key", "value", nx=True) == False # Only set the key if it already exists. assert redis.set("key", "value", xx=True) == True ``` LANGUAGE: python CODE: ``` # Set the key to expire in 10 seconds. assert redis.set("key", "value", ex=10) == True # Set the key to expire in 10000 milliseconds. assert redis.set("key", "value", px=10000) == True ``` LANGUAGE: python CODE: ``` # Get the old value stored at the key. assert redis.set("key", "new-value", get=True) == "old-value" ``` ---------------------------------------- TITLE: Initialize Upstash Redis in Node.js/Browser DESCRIPTION: Demonstrates how to initialize an Upstash Redis client in Node.js or browser environments. Configuration can be loaded from explicit URL/token environment variables or directly using `Redis.fromEnv()`. This method is suitable for platforms like Vercel, Netlify, and AWS Lambda. SOURCE: https://upstash.com/docs/redis/sdks/ts/deployment.mdx LANGUAGE: ts CODE: ``` import { Redis } from "@upstash/redis" const redis = new Redis({ url: , token: , }) // or load directly from env const redis = Redis.fromEnv() ``` ---------------------------------------- TITLE: Fetch and Display Coin Data with Apollo GraphQL in Next.js DESCRIPTION: This Next.js component (`index.js`) defines a GraphQL query (`GET_COIN_LIST`) to retrieve a range of coin data from the 'coins' Redis list via the Upstash GraphQL API. It utilizes Apollo's `useQuery` hook to manage loading states and errors, parses the JSON string results, and dynamically renders a table displaying cryptocurrency names, prices, and images. A loading indicator is shown while data is being fetched. SOURCE: https://upstash.com/docs/redis/tutorials/coin_price_list.mdx LANGUAGE: javascript CODE: ``` import Head from "next/head"; import styles from "../styles/Home.module.css"; import { gql, useQuery } from "@apollo/client"; import React from "react"; const GET_COIN_LIST = gql` query { redisLRange(key: "coins", start: 0, stop: 6) } `; export default function Home() { let coins = []; const { loading, error, data } = useQuery(GET_COIN_LIST); if (!loading && !error) { for (let x of data.redisLRange) { let dd = JSON.parse(x); coins.push(dd); } } return (
Create Next App

Coin Price List

{!loading ? ( coins.map((item, ind) => ( )) ) : ( )}
{item.name} ${item.price}
); } ``` ---------------------------------------- TITLE: FastAPI Application with Redis Caching DESCRIPTION: Defines a FastAPI application that fetches weather data for a given city. It integrates with Upstash Redis to implement caching: it first checks if the data exists in the cache, otherwise it fetches from an external API and stores the result in Redis with a 10-minute expiration. SOURCE: https://upstash.com/docs/redis/tutorials/python_fastapi_caching.mdx LANGUAGE: python CODE: ``` from fastapi import FastAPI from upstash_redis import Redis import requests import os app = FastAPI() # Connect to Redis using environment variables redis = Redis.from_env() # Mock API endpoint for weather data WEATHER_API_URL = "https://api.weatherapi.com/v1/current.json" API_KEY = os.getenv("WEATHER_API_KEY") @app.get("/weather/{city}") def get_weather(city: str): cache_key = f"weather:{city}" # Check if the data exists in cache cached_data = redis.get(cache_key) if cached_data: return {"source": "cache", "data": cached_data} # Fetch data from external API response = requests.get(f"{WEATHER_API_URL}?key={API_KEY}&q={city}") weather_data = response.json() # Store the data in Redis cache with a 10-minute expiration redis.setex(cache_key, 600, weather_data) return {"source": "api", "data": weather_data} ``` ---------------------------------------- TITLE: Simple Node.js Express Application with Redis Counter DESCRIPTION: This JavaScript code defines a basic Express.js server that interacts with an Upstash Redis instance. It increments a 'counter' key in Redis on every GET request to the root path and displays the current visitor number. The application uses the `redis` client library and `util.promisify` for asynchronous Redis operations, connecting via the `REDIS_URL` environment variable. SOURCE: https://upstash.com/docs/redis/quickstarts/fly.mdx LANGUAGE: js CODE: ``` const express = require("express"); const redis = require("redis"); const { promisify } = require("util"); const app = express(); const client = redis.createClient(process.env.REDIS_URL); const getAsync = promisify(client.get).bind(client); const setAsync = promisify(client.set).bind(client); app.get("/", async (req, res) => { const value = await getAsync("counter"); await setAsync("counter", parseInt(value || 0) + 1); res.send(`Hello, visitor number ${value || 0}!`); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); ``` ---------------------------------------- TITLE: Increment Key Value in Redis (Python) DESCRIPTION: Demonstrates how to use the `INCR` command in Upstash Redis with a Python client. It shows setting an initial integer value for a key and then incrementing it, asserting the new value. This command handles non-existent keys by initializing them to 0 before incrementing. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/string/incr.mdx LANGUAGE: py CODE: ``` redis.set("key", 6) assert redis.incr("key") == 7 ``` ---------------------------------------- TITLE: Implement Caching in Laravel TodoController for CRUD Operations DESCRIPTION: Integrates caching into the `TodoController`'s CRUD methods using Laravel's `Cache::flexible` for retrieval and `Cache::forget` for invalidation. It defines cache keys and Time-To-Live (TTL) values, ensuring data freshness across read and write operations by invalidating relevant caches upon data modification. SOURCE: https://upstash.com/docs/redis/tutorials/laravel_caching.mdx LANGUAGE: php CODE: ``` validate([ 'title' => 'required|string|max:255', ]); $todo = Todo::create($request->all()); // Invalidate the todos cache Cache::forget(self::CACHE_KEY); return response()->json($todo, Response::HTTP_CREATED); } /** * Display the specified resource. */ public function show(Todo $todo): Todo { return Cache::flexible( "todo.{$todo->id}", self::CACHE_TTL, function () use ($todo) { return $todo; } ); } /** * Update the specified resource in storage. */ public function update(Request $request, Todo $todo): JsonResponse { $request->validate([ 'title' => 'required|string|max:255', ]); $todo->update($request->all()); // Invalidate both the collection and individual todo cache Cache::forget(self::CACHE_KEY); Cache::forget("todo.{$todo->id}"); return response()->json($todo); } /** * Remove the specified resource from storage. */ public function destroy(Todo $todo): JsonResponse { $todo->delete(); // Invalidate both the collection and individual todo cache Cache::forget(self::CACHE_KEY); Cache::forget("todo.{$todo->id}"); return response()->json(null, Response::HTTP_NO_CONTENT); } } ``` ---------------------------------------- TITLE: Backend API: Create New Feature (Next.js, ioredis) DESCRIPTION: This Next.js API endpoint (`/api/create`) allows users to add new feature suggestions to the 'roadmap' Sorted Set in Upstash Redis. It uses the `ZADD` command with the 'NX' flag to prevent duplicate entries and includes validation for the feature title's presence and length. SOURCE: https://upstash.com/docs/redis/tutorials/roadmapvotingapp.mdx LANGUAGE: javascript CODE: ``` import Redis from "ioredis"; import { fixUrl } from "./utils"; module.exports = async (req, res) => { let redis = new Redis(fixUrl(process.env.REDIS_URL)); const body = req.body; const title = body["title"]; if (!title) { redis.quit(); res.json({ error: "Feature can not be empty", }); } else if (title.length < 70) { await redis.zadd("roadmap", "NX", 1, title); redis.quit(); res.json({ body: "success", }); } else { redis.quit(); res.json({ error: "Max 70 characters please.", }); } }; ``` ---------------------------------------- TITLE: Python URL Shortener Application Core Logic DESCRIPTION: This comprehensive Python script defines the main functionalities of the URL shortener. It includes functions for generating unique short codes, storing original URLs in Redis with an optional expiration time, and retrieving the original URL based on a given short code. The script also demonstrates example usage within its `if __name__ == "__main__":` block. SOURCE: https://upstash.com/docs/redis/tutorials/python_url_shortener.mdx LANGUAGE: python CODE: ``` import string import random from upstash_redis import Redis from dotenv import load_dotenv import os # Load environment variables load_dotenv() # Redis connection redis = Redis.from_env() # Characters to generate the short URL from CHARS = string.ascii_letters + string.digits BASE_URL = "https://short.url/" # Function to generate a random string for the short URL def generate_short_code(length=6): return ''.join(random.choices(CHARS, k=length)) # Function to shorten the URL with an expiration time def shorten_url(url, expiration=3600): # Generate a random short code short_code = generate_short_code() # Save the short code in Redis redis.set(short_code, url, ex=expiration) return BASE_URL + short_code # Function to get the original URL from the short URL def get_original_url(short_code): return redis.get(short_code) # Example usage if __name__ == "__main__": original_url = "https://example.com/my-very-long-url" # Shorten the URL short_url = shorten_url(original_url, expiration=600) print(f"Shortened URL: {short_url}") # Get the original URL original_url = get_original_url(short_url.split("/")[-1]) if original_url: print(f"Original URL: {original_url}") else: print("Short URL expired or not found") ``` ---------------------------------------- TITLE: Apply Different Ratelimits for Free and Paid Users DESCRIPTION: This snippet demonstrates how to configure and apply distinct ratelimits for different user groups, such as free and paid users. It utilizes separate `Ratelimit` instances, each with its own prefix and `slidingWindow` configuration, allowing for flexible rate management based on user attributes. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/features.mdx LANGUAGE: ts CODE: ``` import { Redis } from "@upstash/redis"; import { Ratelimit } from "@upstash/ratelimit"; const redis = Redis.fromEnv(); const ratelimit = { free: new Ratelimit({ redis, analytics: true, prefix: "ratelimit:free", limiter: Ratelimit.slidingWindow(10, "10s"), }), paid: new Ratelimit({ redis, analytics: true, prefix: "ratelimit:paid", limiter: Ratelimit.slidingWindow(60, "10s"), }), }; await ratelimit.free.limit(ip); // or for a paid user you might have an email or userId available: await ratelimit.paid.limit(userId); ``` ---------------------------------------- TITLE: Client-side Feature Management (Next.js React Component) DESCRIPTION: This JavaScript code from the `Home` React component handles user interactions for a roadmap voting application. It includes functions to refresh feature data, vote on features, add new feature suggestions, and register email notifications, all by making `fetch` requests to various backend APIs. SOURCE: https://upstash.com/docs/redis/tutorials/roadmapvotingapp.mdx LANGUAGE: javascript CODE: ``` import Head from 'next/head' import { ToastContainer, toast } from 'react-toastify'; import * as React from "react"; class Home extends React.Component { ... refreshData() { fetch("api/list") .then(res => res.json()) .then( (result) => { this.setState({ isLoaded: true, items: result.body }); this.inputNewFeature.current.value = ""; }, (error) => { this.setState({ isLoaded: true, error }); } ) } vote(event, title) { const requestOptions = { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({"title": title}) }; console.log(requestOptions); fetch('api/vote', requestOptions) .then(response => response.json()).then(data => { console.log(data) if(data.error) { toast.error(data.error, {hideProgressBar: true, autoClose: 3000}); } else { this.refreshData() } }) } handleNewFeature(event) { const requestOptions = { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({"title": this.inputNewFeature.current.value}) }; fetch('api/create', requestOptions) .then(response => response.json()).then(data => { if(data.error) { toast.error(data.error, {hideProgressBar: true, autoClose: 5000}); } else { toast.info("Your feature has been added to the list.", {hideProgressBar: true, autoClose: 3000}); this.refreshData() } }); event.preventDefault(); } handleNewEmail(event) { const requestOptions = { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({"email": this.inputEmail.current.value}) }; console.log(requestOptions); fetch('api/addemail', requestOptions) .then(response => response.json()).then(data => { if(data.error) { toast.error(data.error, {hideProgressBar: true, autoClose: 3000}); } else { toast.info("Your email has been added to the list.", {hideProgressBar: true, autoClose: 3000}); this.refreshData() } }); event.preventDefault(); } } export default Home; ``` ---------------------------------------- TITLE: Supabase Function Redis Counter Logic (TypeScript) DESCRIPTION: Implements the core logic for the Supabase function. It connects to Upstash Redis, increments a regional counter based on the 'DENO_REGION' environment variable (or 'localhost'), and returns the aggregated counter hash. SOURCE: https://upstash.com/docs/redis/quickstarts/supabase.mdx LANGUAGE: ts CODE: ``` import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; import { Redis } from "https://deno.land/x/upstash_redis@v1.19.3/mod.ts"; console.log(`Function "upstash-redis-counter" up and running!`); serve(async (_req) => { try { const redis = new Redis({ url: Deno.env.get("UPSTASH_REDIS_REST_URL")!, token: Deno.env.get("UPSTASH_REDIS_REST_TOKEN")!, }); const deno_region = Deno.env.get("DENO_REGION"); if (deno_region) { // Increment region counter await redis.hincrby("supa-edge-counter", deno_region, 1); } else { // Increment localhost counter await redis.hincrby("supa-edge-counter", "localhost", 1); } // Get all values const counterHash: Record | null = await redis.hgetall( "supa-edge-counter" ); const counters = Object.entries(counterHash!) .sort(([, a], [, b]) => b - a) // sort desc .reduce( (r, [k, v]) => ({ total: r.total + v, regions: { ...r.regions, [k]: v }, }), { total: 0, regions: {}, } ); return new Response(JSON.stringify({ counters }), { status: 200 }); } catch (error) { return new Response(JSON.stringify({ error: error.message }), { status: 200, }); } }); ``` ---------------------------------------- TITLE: Next.js App Router Home Page with Upstash Redis Counter DESCRIPTION: This TypeScript React component for `/app/page.tsx` demonstrates how to integrate Upstash Redis to create a simple page view counter. It initializes the Redis client, increments a key named 'counter', and displays the current count on the page. SOURCE: https://upstash.com/docs/redis/quickstarts/nextjs-app-router.mdx LANGUAGE: tsx CODE: ``` import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); export default async function Home() { const count = await redis.incr("counter"); return (

Counter: {count}

) } ``` ---------------------------------------- TITLE: Upstash Redis Environment Variables for Next.js App DESCRIPTION: This code block shows the required environment variables for connecting to an Upstash Redis database. `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` should be replaced with your actual credentials obtained from the Upstash Console. SOURCE: https://upstash.com/docs/redis/quickstarts/nextjs-app-router.mdx LANGUAGE: plaintext CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Initialize Upstash Redis Client with Direct Configuration DESCRIPTION: This TypeScript example demonstrates how to initialize the Upstash Redis client by directly providing the REST URL and token. It then performs an asynchronous `get` operation to retrieve data from Redis, logging the result or any encountered errors. SOURCE: https://upstash.com/docs/redis/howto/connectwithupstashredis.mdx LANGUAGE: typescript CODE: ``` import { Redis } from "@upstash/redis"; const redis = new Redis({ url: "UPSTASH_REDIS_REST_URL", token: "UPSTASH_REDIS_REST_TOKEN" }); (async () => { try { const data = await redis.get("key"); console.log(data); } catch (error) { console.error(error); } })(); ``` ---------------------------------------- TITLE: Implement Basic Rate Limiting with Upstash Ratelimit DESCRIPTION: This TypeScript example demonstrates how to initialize `@upstash/ratelimit` with an Upstash Redis instance, configure a sliding window limiter, and apply it to an endpoint to control request rates. It shows how to check for rate limit success and handle blocked requests. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted.mdx LANGUAGE: ts CODE: ``` import { Ratelimit } from "@upstash/ratelimit"; // for deno: see above import { Redis } from "@upstash/redis"; // Create a new ratelimiter, that allows 10 requests per 10 seconds const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), analytics: true, /** * Optional prefix for the keys used in redis. This is useful if you want to share a redis * instance with other applications and want to avoid key collisions. The default prefix is * "@upstash/ratelimit" */ prefix: "@upstash/ratelimit", }); // Use a constant string to limit all requests with a single ratelimit // Or use a userID, apiKey or ip address for individual limits. const identifier = "api"; const { success } = await ratelimit.limit(identifier); if (!success) { return "Unable to process at this time"; } doExpensiveCalculation(); return "Here you go!"; ``` ---------------------------------------- TITLE: Perform Basic Redis Operations (Set/Get) with Upstash Client DESCRIPTION: This example demonstrates how to perform fundamental Redis `set` and `get` operations using both synchronous and asynchronous `upstash-redis` clients. It shows the process of initializing the client, typically from environment variables, and then executing commands. Pay close attention to the use of the `await` keyword for handling asynchronous operations correctly. SOURCE: https://upstash.com/docs/redis/sdks/py/gettingstarted.mdx LANGUAGE: python CODE: ``` 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")) ``` ---------------------------------------- TITLE: Connect to Upstash Redis using jedis (Java) DESCRIPTION: This example demonstrates connecting to an Upstash Redis database using the `jedis` library in Java. It creates a Jedis instance with the endpoint, port, and SSL enabled, authenticates with the password, and then sets and retrieves a string value. SOURCE: https://upstash.com/docs/redis/howto/connectclient.mdx LANGUAGE: java CODE: ``` Jedis jedis = new Jedis("YOUR_ENDPOINT", "YOUR_PORT", true); jedis.auth("YOUR_PASSWORD"); jedis.set("foo", "bar"); String value = jedis.get("foo"); System.out.println(value); ``` ---------------------------------------- TITLE: Configure Upstash Redis Environment Variables DESCRIPTION: These commands set the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables, which are required to connect to your Upstash Redis database. Replace placeholders with your actual credentials. SOURCE: https://upstash.com/docs/redis/quickstarts/vercel-python-runtime.mdx LANGUAGE: shell CODE: ``` export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Set Environment Variables for Cloudflare Worker (Wrangler) DESCRIPTION: Commands to set `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` as secrets in a Cloudflare Worker project using the `wrangler secret put` command-line tool. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted.mdx LANGUAGE: bash CODE: ``` npx wrangler secret put UPSTASH_REDIS_REST_URL ``` LANGUAGE: bash CODE: ``` npx wrangler secret put UPSTASH_REDIS_REST_TOKEN ``` ---------------------------------------- TITLE: Python Multithreaded Web Scraper with Redis Caching DESCRIPTION: This comprehensive Python code implements a multithreaded web scraper. It uses `threading` to process URL groups concurrently, `requests` for HTTP requests, and `upstash-redis` for caching. The `Scraper` class checks Redis for cached responses before making new HTTP requests, storing new responses in Redis to optimize performance and reduce redundant fetches across threads. SOURCE: https://upstash.com/docs/redis/tutorials/python_multithreading.mdx LANGUAGE: python CODE: ``` import threading import requests from upstash_redis import Redis from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() # Initialize Redis client redis = Redis.from_env() # Group URLs by thread, with one or two overlapping URLs across groups urls_to_scrape_groups = [ [ 'https://httpbin.org/delay/1', 'https://httpbin.org/delay/4', 'https://httpbin.org/delay/2', 'https://httpbin.org/delay/5', 'https://httpbin.org/delay/3', ], [ 'https://httpbin.org/delay/5', # Overlapping URL 'https://httpbin.org/delay/6', 'https://httpbin.org/delay/7', 'https://httpbin.org/delay/2', # Overlapping URL 'https://httpbin.org/delay/8', ], [ 'https://httpbin.org/delay/3', # Overlapping URL 'https://httpbin.org/delay/9', 'https://httpbin.org/delay/10', 'https://httpbin.org/delay/4', # Overlapping URL 'https://httpbin.org/delay/11', ], ] class Scraper(threading.Thread): def __init__(self, urls): threading.Thread.__init__(self) self.urls = urls self.results = {} def run(self): for url in self.urls: cache_key = f"url:{url}" # Attempt to retrieve cached response cached_response = redis.get(cache_key) if cached_response: print(f"[CACHE HIT] {self.name} - URL: {url}") self.results[url] = cached_response continue # Skip to the next URL if cache is found # If no cache, perform the HTTP request print(f"[FETCHING] {self.name} - URL: {url}") response = requests.get(url) if response.status_code == 200: self.results[url] = response.text # Store the response in Redis cache redis.set(cache_key, response.text) else: print(f"[ERROR] {self.name} - Failed to retrieve {url}") self.results[url] = None def main(): threads = [] for urls in urls_to_scrape_groups: scraper = Scraper(urls) threads.append(scraper) scraper.start() # Wait for all threads to complete for scraper in threads: scraper.join() print("\nScraping results:") for scraper in threads: for url, result in scraper.results.items(): print(f"Thread {scraper.name} - URL: {url} - Response Length: {len(result) if result else 'Failed'}") if __name__ == "__main__": main() ``` ---------------------------------------- TITLE: Next.js Home Page Redis Counter Implementation DESCRIPTION: This TypeScript/React code demonstrates how to modify the Next.js home page (`/app/page.tsx`) to interact with Redis. It initializes a Redis client, increments a 'counter' key, and displays the current count, showcasing basic data retrieval and update operations. SOURCE: https://upstash.com/docs/redis/tutorials/nextjs_with_redis.mdx LANGUAGE: tsx CODE: ``` import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); export default async function Home() { const count = await redis.incr("counter"); return (

Counter: {count}

) } ``` ---------------------------------------- TITLE: FastAPI Session Management Application with Redis DESCRIPTION: Implements a FastAPI application demonstrating user session management using Upstash Redis. It includes endpoints for user login, profile access with sliding session expiration, and logout, all leveraging Redis for storing and managing session data. SOURCE: https://upstash.com/docs/redis/tutorials/python_session.mdx LANGUAGE: Python CODE: ``` from fastapi import FastAPI, Response, Cookie, HTTPException from pydantic import BaseModel from upstash_redis import Redis from dotenv import load_dotenv import uuid # Load environment variables load_dotenv() redis = Redis.from_env() app = FastAPI() SESSION_TIMEOUT_SECONDS = 900 # 15 minutes # Define the request body model for login class LoginRequest(BaseModel): username: str @app.post("/login/") async def login(request: LoginRequest, response: Response): session_id = str(uuid.uuid4()) redis.hset(f"session:{session_id}", values={"user": request.username, "status": "active"}) redis.expire(f"session:{session_id}", SESSION_TIMEOUT_SECONDS) response.set_cookie(key="session_id", value=session_id, httponly=True) return {"message": "Logged in successfully", "session_id": session_id} @app.get("/profile/") async def get_profile(session_id: str = Cookie(None)): if not session_id: raise HTTPException(status_code=403, detail="No session cookie found") session_data = redis.hgetall(f"session:{session_id}") if not session_data: response = Response() response.delete_cookie(key="session_id") # Clear the expired cookie raise HTTPException(status_code=404, detail="Session expired") # Update the session expiration time (sliding expiration) redis.expire(f"session:{session_id}", SESSION_TIMEOUT_SECONDS) return {"session_id": session_id, "session_data": session_data} @app.post("/logout/") async def logout(response: Response, session_id: str = Cookie(None)): if session_id: redis.delete(f"session:{session_id}") response.delete_cookie(key="session_id") return {"message": "Logged out successfully"} ``` ---------------------------------------- TITLE: Set Upstash Redis Environment Variables DESCRIPTION: These bash commands export the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables. These variables are crucial for the Node.js application to authenticate and connect to the Upstash Redis database. SOURCE: https://upstash.com/docs/redis/quickstarts/koyeb.mdx LANGUAGE: bash CODE: ``` export UPSTASH_REDIS_REST_URL="" export UPSTASH_REDIS_REST_TOKEN="" ``` ---------------------------------------- TITLE: Set Upstash Redis Environment Variables (Shell) DESCRIPTION: These shell commands set the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables. These variables are crucial for the Python application to establish a connection with the Upstash Redis database. SOURCE: https://upstash.com/docs/redis/tutorials/python_url_shortener.mdx LANGUAGE: shell CODE: ``` export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Producer Function for Employee Registration Queue DESCRIPTION: Illustrates a JavaScript AWS Lambda function acting as a producer, using the Bull library to add new employee registration events to a Redis-backed task queue. It configures the queue with Redis connection details (host, port, password) and specific settings to manage job processing intervals, and returns a success message upon enqueuing the event. SOURCE: https://upstash.com/docs/redis/tutorials/job_processing.mdx LANGUAGE: JavaScript CODE: ``` var Queue = require("bull"); var settings = { stalledInterval: 300000, // How often check for stalled jobs (use 0 for never checking). guardInterval: 5000, // Poll interval for delayed jobs and added jobs. drainDelay: 300, // A timeout for when the queue is in drained state (empty waiting for jobs). }; module.exports.hello = async (event) => { var taskQueue = new Queue( "employee registration", { redis: { port: 32016, host: "us1-upward-ant-32016.upstash.io", password: "ake4ff120d6b4216df220736be7eab087", tls: {}, }, }, settings ); await taskQueue.add({ event: event }); // TODO save the employee record to a database return { message: "New employee event enqueued! 34", event }; }; ``` ---------------------------------------- TITLE: Connect to Upstash Redis using redis-py (Python) DESCRIPTION: This example illustrates connecting to an Upstash Redis database using the `redis-py` library in Python. It initializes a Redis client with the host, port, password, and enables SSL, then performs a `set` and `get` operation. SOURCE: https://upstash.com/docs/redis/howto/connectclient.mdx LANGUAGE: python CODE: ``` import redis r = redis.Redis( host= 'YOUR_ENDPOINT', port= 'YOUR_PORT', password= 'YOUR_PASSWORD', ssl=True) r.set('foo','bar') print(r.get('foo')) ``` ---------------------------------------- TITLE: Upstash Redis Environment Variables Configuration DESCRIPTION: This snippet illustrates how to configure the essential environment variables for connecting to an Upstash Redis database. It includes placeholders for the REST URL and Token, which are required for authentication and API access. SOURCE: https://upstash.com/docs/redis/tutorials/nextjs_with_redis.mdx LANGUAGE: shell CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Separate Client Instances for Read and Write Operations DESCRIPTION: Demonstrates a common pattern where write and read requests might originate from different client instances or API endpoints. This setup, without explicit sync token management, can lead to read-after-write consistency issues on read replicas. The example shows a write function, a read function, and their sequential invocation. SOURCE: https://upstash.com/docs/redis/howto/readyourwrites.mdx LANGUAGE: TypeScript CODE: ``` export const writeRequest = async () => { const redis = Redis.fromEnv(); const randomKey = nanoid(); await redis.set(randomKey, "value"); return randomKey; }; export const readRequest = async (randomKey: string) => { const redis = Redis.fromEnv(); const value = await redis.get(randomKey); return value; }; const randomKey = await writeRequest(); await readRequest(randomKey); ```