pythonflaskwsgi

AttributeError: 'Flask' object has no attribute 'before_first_request' in Flask 3.x


I'm trying to run init function when flask app run. Here's server.py:

from .parser import Parser
app = Flask(config().get("FLASK_APP"))

parser = None

@app.before_first_request
def init():
  parser = Parser()

Here's wsgi.py:


import logging
from src.utils.config import config

host = config().get("FLASK_HOST")
port = config().get("FLASK_PORT")
env = config().get("FLASK_ENV")
is_dev = env == "dev"
logging.basicConfig(
  format='[%(asctime)s][%(levelname)s][%(message)s]',
  level=logging.INFO if is_dev else logging.WARNING,
  datefmt='%Y-%m-%d %H:%M:%S'
)

from src.api.server import app
if __name__ == '__main__':
  app.run(
    host=host, 
    port=port,
    debug=is_dev,
    threaded=True 
  )

And i'm getting the error AttributeError: 'Flask' object has no attribute 'before_first_request'. When i'm running the server.py like this:

from .parser import Parser
app = Flask(config().get("FLASK_APP"))

parser = Parser()

The parser runs twice.

I'm using Flask 3.0.0, as i see this decorator is deprecated. Are there any other solutions for Flask 3.0.0 version?

I've checked the flask documentation but didn't find any alternatives for before_first_request decorator.


Solution

  • Suddenly i found the solution. The problem as i see is in the flask's reloader, so i just disabled this feature in the app.run bootstrap function.
    Here's detailed info by Sean's answer https://stackoverflow.com/a/9476701/11988818
    For now, my application runs once. And there's no needs in the before_first_request decorator anymore.