Skip to content
Myr

Break reference cycle created by default in Flask instances.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Flask instances with static folders were creating a reference cycle via their "static" view function (which held a strong reference back to the Flask instance to call its `send_static_file` method). This prevented CPython from freeing the memory for a Flask instance when all external references to it were released. Now use a weakref for the back reference to avoid this.

authored by Bogdan Opanchuk · committed by GitHub · parent 4e8b020 · Browse files · 2 files+29 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Joshua Bronson <jab@users.noreply.github.com>

Diff stats

2 files+29 added−1 removed

  • tests:+24 added−0 removed
  • other:+5 added−1 removed

2 files+29 added−1 removed

modified:src/flask/app.py+5 added-1 removed
1import os2import sys3import weakref4from datetime import timedelta5from itertools import chain6from threading import Lock7
470 unmodified lines
478 if self.has_static_folder:479 assert (480 bool(static_host) == host_matching481 ), "Invalid static_host/host_matching combination"482 # Use a weakref to avoid creating a reference cycle between the app483 # and the view function (see #3761).484 self_ref = weakref.ref(self)485 self.add_url_rule(486 f"{self.static_url_path}/<path:filename>",487 endpoint="static",488 host=static_host,485 view_func=self.send_static_file,489 view_func=lambda **kw: self_ref().send_static_file(**kw),490 )491492 # Set the name of the Click group in case someone wants to add493 # the app's commands to another CLI tool.
1545 unmodified lines
modified:tests/test_basic.py+24 added
1import gc2import re3import sys4import time5import uuid6import weakref7from datetime import datetime8from platform import python_implementation9from threading import Thread1011import pytest12import werkzeug.serving
5 unmodified lines
1819import flask202122require_cpython_gc = pytest.mark.skipif(23 python_implementation() != "CPython", reason="Requires CPython GC behavior",24)252627def test_options_work(app, client):28 @app.route("/", methods=["GET", "POST"])29 def index():30 return "Hello World"
1946 unmodified lines
1977 app.config["MAX_COOKIE_SIZE"] = 019781979 client.get("/")1980 assert len(recwarn) == 0198119821983@require_cpython_gc1984def test_app_freed_on_zero_refcount():1985 # A Flask instance should not create a reference cycle that prevents CPython1986 # from freeing it when all external references to it are released (see #3761).1987 gc.disable()1988 try:1989 app = flask.Flask(__name__)1990 assert app.view_functions["static"]1991 weak = weakref.ref(app)1992 assert weak() is not None1993 del app1994 assert weak() is None1995 finally:1996 gc.enable()