4

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?

davidism
  • 121,510
  • 29
  • 395
  • 339
Denton Zhou
  • 75
  • 1
  • 8

1 Answers1

8

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.

davidism
  • 121,510
  • 29
  • 395
  • 339