- Flask Framework Cookbook(Second Edition)
- Shalabh Aggarwal
- 180字
- 2021-06-24 13:58:07
How to do it...
We will maintain a set in Redis, which will store the products visited recently. This will be populated whenever we visit a product. The entry will expire in 10 minutes. This change goes in views.py:
from my_app import redis @catalog.route('/product/<id>') def product(id): product = Product.query.get_or_404(id) product_key = 'product-%s' % product.id redis.set(product_key, product.name) redis.expire(product_key, 600) return 'Product - %s, $%s' % (product.name, product.price)
It is good practice to fetch the expire time, that is, 600, from a configuration value. This can be set on the application object in my_app/__init__.py, and can then be fetched from there.
In the preceding method, note the set() and expire() methods on the redis object.
First, we set the product ID using the product_key value in the Redis store.
Then, we set the expire time of the key to 600 seconds.
Now, we will look for the keys that are still alive in the cache and then fetch the products corresponding to these keys and return them:
@catalog.route('/recent-products') def recent_products(): keys_alive = redis.keys('product-*') products = [redis.get(k).decode('utf-8') for k in keys_alive] return jsonify({'products': products})