Learn / Frameworks / Flask / Caching and Background Jobs

Flask · Lesson 12 of 15

Caching and Background Jobs

Flask-Caching with Redis and a simple RQ worker for slow work.

  • Advanced
  • 16 min read
  • 3 objectives

Before this lessonLesson 11: CSRF, XSS and Hardening

What you will learn

  • Cache a view
  • Enqueue a job
  • Run a worker

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Two levers for slow work: cache the result, or do the work somewhere else.

Flask-Caching

from flask_caching import Cache
cache = Cache(config={"CACHE_TYPE": "RedisCache", "CACHE_REDIS_URL": os.environ["REDIS_URL"]})
cache.init_app(app)

@app.route("/popular")
@cache.cached(timeout=60)
def popular():
    return jsonify(Post.query.order_by(Post.views.desc()).limit(10).all())

Invalidate on write: cache.delete("view/popular") after a new post. The simple-cache backend is process-local and wrong for gunicorn.

RQ

# pip install rq redis
from redis import Redis
from rq import Queue
queue = Queue(connection=Redis.from_url(os.environ["REDIS_URL"]))

def send_welcome(email):
    ...

@app.route("/signup", methods=["POST"])
def signup():
    user = create_user(request.form["email"])
    queue.enqueue(send_welcome, user.email)
    return redirect(url_for("index"))
rq worker
Up next · Lesson 13The Flask CLI and ShellCustom flask commands, the shell context and one-off scripts.