how to run the code before the app.run() in flask?
Asked Answered
C

4

9

I'm new on flask.I configured a server with flask+gunicorn.

the code file called test.py like this:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def test():
    return aa+"world!"

if __name__ == '__main__':
    aa = "hello"
    app.run()

run it using:gunicorn -b 0.0.0.0:8080 test:app

I got a mistake:NameError: name 'aa' is not defined.

I want some codes like variable aa runing before gunicorn.

How to do that?

Cocky answered 9/5, 2018 at 9:15 Comment(3)
What is a ? That a is indeed undefined..Aldous
sorry,it is 'aa'.I edited itCocky
And the a+"world" should also be aa?Jemison
G
7

Put in a small block just before your @app.route and you dont need the last block in the question

 @app.before_first_request
 def _declareStuff():
     global aa
     aa='hello'
Glenine answered 9/5, 2018 at 9:20 Comment(0)
W
2

As of Flask 2.2, the @app.before_first_request decorator suggested by Vipluv in their answer is deprecated and will be removed in 2.3.

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

The equivalent can be done by manually pushing the app context, as suggested by Enkum :

# In place of something like this
@app.before_first_request
def create_tables():
    db.create_all()
    ...

# USE THIS INSTEAD
with app.app_context():
    db.create_all()
Waine answered 6/1, 2023 at 14:12 Comment(1)
This has the caveat of being run every time your app starts, even when not running the server. This may not be desirable if you make heavy use of app.cli.Tracey
V
0

Just declare aa outside of "__main__", in the global scope of the file.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def test():
    return aa+"world!"

aa = "hello"

if __name__ == '__main__':
    app.run()

The code in the if __name__ == '__main__': block executes only if the Python code is run as a script, e.g., from the command line. Gunicorn imports the file, so in that case the code in __main__ will not be executed.


Note that if it is your intention to modify the value of aa then different requests can produce different results depending on how many requests each gunicorn worker process has handled. e.g.:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def test():
    global counter
    counter += 1
    return "{} world! {}".format('aa', counter)

counter = 0

if __name__ == '__main__':
    app.run()

Run the above script with more than one worker (gunicorn -w 2 ...) and make several requests to the URL. You should see that the counter is not always contiguous.

Venerate answered 9/5, 2018 at 9:52 Comment(0)
H
0
  1. The script creates a Flask web application.

  2. It defines a function (declareStuff) to be executed before each incoming request. Inside this function, it sets a value ('hello') to the attribute 'aa' of Flask's special g object.

  3. The script defines a route for the root URL ('/') and a corresponding function (test). When a user accesses this URL, the function returns a response that includes the value stored in g.aa.

  4. The application is configured to run on host '0.0.0.0' and port '8080' with debugging enabled.

In summary, the script initializes a Flask app, uses the g object to store data to each request, and responds to the root URL with the stored value followed by ' world!'. This demonstrates the use of Flask's before_request hook and the g object for managing data during the processing of HTTP requests.

from flask import Flask, g

app = Flask(__name__)

# This function is executed before each request
@app.before_request
def declareStuff():
    # Set a value 'hello' to the attribute 'aa' of the 'g' object
    g.aa = 'hello'

# Define a route and corresponding function for the root URL
@app.route('/')
def test():
    # Return a response composed of the value stored in g.aa followed by ' world!'
    return f"{g.aa} world!"

# Run the Flask application
if __name__ == '__main__':
    # Run the application on host 0.0.0.0, port 8080, with debugging enabled
    app.run(host="0.0.0.0", port=8080, debug=True)
Habergeon answered 8/1 at 23:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.