Flask App with Caching Random Fruit Word Generation

  • Share this:

Code introduction


This code snippet defines a Flask application that uses the flask-caching library to cache the result of a random word generation function. This function returns a random fruit name each time it is called.


Technology Stack : Flask, Flask-Caching, Python standard library

Code Type : Flask extension

Code Difficulty : Intermediate


                
                    
from flask_caching import Cache
from flask import Flask
import random

app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})

def random_word():
    # This function generates a random word using the random module from Python's standard library.
    words = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape', 'honeydew']
    return random.choice(words)

@cache.cached(timeout=50, key_prefix='random_word')
def get_random_word():
    # This function uses Flask-Caching to cache the result of the random_word function for 50 seconds.
    return random_word()

# Flask application entry point
if __name__ == '__main__':
    app.run(debug=True)