From 0ed8a458bacd80ed8533c6da1e88d860f45c0d6e Mon Sep 17 00:00:00 2001 From: Will Chen Date: Thu, 9 May 2024 16:39:36 -0700 Subject: [PATCH] Parse flags in wsgi_app --- mesop/server/wsgi_app.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/mesop/server/wsgi_app.py b/mesop/server/wsgi_app.py index 1024802a9..a73a40242 100644 --- a/mesop/server/wsgi_app.py +++ b/mesop/server/wsgi_app.py @@ -1,5 +1,7 @@ +import sys from typing import Any, Callable +from absl import flags from flask import Flask from mesop.runtime import enable_debug_mode @@ -43,6 +45,17 @@ def create_app( return App(flask_app=flask_app) +flask_app = None + + def wsgi_app(environ: dict[Any, Any], start_response: Callable[..., Any]): - app = create_app(prod_mode=True) - return app._flask_app.wsgi_app(environ, start_response) # type: ignore + # Lazily create and reuse a flask app singleton to avoid + # the overhead for each WSGI request. + global flask_app + if not flask_app: + # Parse the flags before creating the app otherwise you will + # get UnparsedFlagAccessError. + flags.FLAGS(sys.argv) + flask_app = create_app(prod_mode=True) + + return flask_app._flask_app.wsgi_app(environ, start_response) # type: ignore