In this quickstart tutorial, we will demonstrate how to use Django with Upstash Redis to build a simple web application that increments a counter every time the homepage is accessed.
First, install Django and the Upstash Redis client for Python:
Create a Redis database using the Upstash Console or Upstash CLI and export the UPSTASH_REDIS_REST_URL
and UPSTASH_REDIS_REST_TOKEN
to your environment:
You can also use python-dotenv
to load environment variables from your .env
file.
Create a new Django project:
In myproject/settings.py
, add your new app (myapp
) to the INSTALLED_APPS
list.
In myapp/views.py
, add the following:
In myproject/urls.py
, connect the view to a URL pattern:
Run the development server:
Visit http://127.0.0.1:8000/
in your browser, and the counter will increment with each page refresh.
Redis Setup: We use the Upstash Redis client to connect to our Redis database using the environment variables UPSTASH_REDIS_REST_URL
and UPSTASH_REDIS_REST_TOKEN
. The Redis.from_env()
method initializes this connection.
Increment Counter: In the index
view, we increment the counter
key each time the homepage is accessed. If the key doesn’t exist, Redis creates it and starts counting from 1.
Display the Count: The updated count is returned as an HTTP response each time the page is loaded.
In this quickstart tutorial, we will demonstrate how to use Django with Upstash Redis to build a simple web application that increments a counter every time the homepage is accessed.
First, install Django and the Upstash Redis client for Python:
Create a Redis database using the Upstash Console or Upstash CLI and export the UPSTASH_REDIS_REST_URL
and UPSTASH_REDIS_REST_TOKEN
to your environment:
You can also use python-dotenv
to load environment variables from your .env
file.
Create a new Django project:
In myproject/settings.py
, add your new app (myapp
) to the INSTALLED_APPS
list.
In myapp/views.py
, add the following:
In myproject/urls.py
, connect the view to a URL pattern:
Run the development server:
Visit http://127.0.0.1:8000/
in your browser, and the counter will increment with each page refresh.
Redis Setup: We use the Upstash Redis client to connect to our Redis database using the environment variables UPSTASH_REDIS_REST_URL
and UPSTASH_REDIS_REST_TOKEN
. The Redis.from_env()
method initializes this connection.
Increment Counter: In the index
view, we increment the counter
key each time the homepage is accessed. If the key doesn’t exist, Redis creates it and starts counting from 1.
Display the Count: The updated count is returned as an HTTP response each time the page is loaded.