Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Flask methods like before_request when using Connexion

I'm building an API using Connexion, so I'm using app = connexion.FlaskApp(__name__) instead of instead of Flask(__name__).

I want to add before_request and after_request handlers to open and close a database connection. However, since app is a connexion.FlaskApp object, those decorator methods don't exist.

@app.before_request
def before_request():
    g.db = models.db
    g.db.connection()


@app.after_request
def after_request():
    g.db.close()

How can I use before_request and other Flask methods when I'm using Connexion?

like image 278
Denton Zhou Avatar asked Nov 05 '25 14:11

Denton Zhou


1 Answers

The Connexion instance stores the Flask instance as the app attribute. You can still use all the things available to Flask through that.

app = connexion.FlaskApp(__name__)

@app.app.before_request
def open_db():
    ...

Connexion itself does this, for example their route method passes to self.app.route.

like image 71
davidism Avatar answered Nov 07 '25 11:11

davidism



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!