Flask deprecated before_first_request how to update

Publish date: 2024-05-19

I'm learning web development for simple applications and I've created one that uses before_first_request decorator. According with the new release notes, the before_first_request is deprecated and will be removed from Flask 2.3:

Deprecated since version 2.2: Will be removed in Flask 2.3. Run setup code when creating the application instead.

I don't understand how I can update my code to be complacent with Flask 2.3 and still run a function at first request without using before_first_request. Could some kind soul give me an example?

1

3 Answers

I don't know if this is answered but for anyone looking for the answer:

in place of the @app.before_first_request decorated function use the app instance like this: i.e.

# In place of something like this @app.before_first_request def create_tables(): db.create_all() ... # push context manually to app with app.app_context(): db.create_all() 
5

In my case, I was using pytest to test the API and the package flask_monitoringdashboard to monitor my app performance, but the latest version of this last package uses the before_first_request method in the code.

The package team solved this issue one month ago in this commit, but they do not release a new version of the package until now.

  • You can solve this problem manually by applying the upper commit to the package code.
  • You can suppress the warning like the below:
  • import warnings import flask_monitoringdashboard as monitoring_dashboard from your_package import create_app() app = create_app() with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) monitoring_dashboard.config.init_from(file=flask_monitoring_file_path) monitoring_dashboard.bind(app) 
  • If you are having this issue with pytest, try to not execute the code that binds the app with the dashboard in your tests, like not having the binding code in the create_app function.
  • @app.before_first_request def before_first_request(): my_fun() 

    can be replaced with

    app.before_request_funcs = [(None, my_fun())] 

    my_fun() will be run before any request.

    1

    ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobmxtZ2V9dX2On6Oaq5tisaa80Z6amqyVmXqjscWoqZ5llp6%2FtMCMq5yqrZWowW60zrBkraddqr2lrdOe