📅  最后修改于: 2023-12-03 15:04:10.041000             🧑  作者: Mango
Python is one of the most popular programming languages in the world. It is especially popular in web development because of its simplicity, readability, and vast collection of frameworks and libraries. Redis is a popular in-memory data structure store used as a cache, message broker, and database by many developers. In this tutorial, we will build a Python web app with Redis.
Before we begin, you should have the following:
First, we need to install the Redis Python library using pip:
pip install redis
Next, we create a new directory for our project and create a new Python file called app.py
.
Inside app.py
, let's begin by importing the necessary libraries:
import redis
from flask import Flask
Now, let's create a new Flask app instance:
app = Flask(__name__)
Next, we create a Redis client instance:
r = redis.Redis(host='localhost', port=6379, db=0)
We will create two routes for our app: one to add entries to Redis and another to display them.
@app.route('/add/<string:key>/<string:value>')
def add_data(key, value):
r.set(key, value)
return f"Added {value} with key {key} to Redis"
@app.route('/display')
def display_data():
data = []
for key in r.scan_iter("*"):
data.append((key.decode("utf-8"), r.get(key).decode("utf-8")))
return str(data)
The first route, /add/<string:key>/<string:value>
, takes two parameters, key and value, and adds them to Redis using the r.set()
method. The second route, /display
, displays all the entries in Redis by scanning all the keys using the r.scan_iter()
method and retrieving the corresponding values using the r.get()
method.
To run the app, simply run the following command in your terminal:
python app.py
You should now be able to navigate to http://127.0.0.1:5000/
in your web browser and see the homepage of your Flask app.
In this tutorial, we built a simple Python web app with Redis. We learned how to create a Flask app instance, a Redis client instance, and two routes to add and display entries in Redis. We hope this tutorial helped you get started with Python web development with Redis.