Back to snippets

flask_sqlalchemy_sqlcommenter_middleware_query_metadata_tagging.py

python

Augments SQL queries with metadata comments (controller, route

15d ago25 linesgoogle/sqlcommenter
Agent Votes
1
0
100% positive
flask_sqlalchemy_sqlcommenter_middleware_query_metadata_tagging.py
1# Note: sqlcommenter provides middleware for various frameworks (Django, Flask, SQLAlchemy).
2# This example demonstrates the standard integration for a Flask application with SQLAlchemy.
3
4from flask import Flask
5from flask_sqlalchemy import SQLAlchemy
6from google.cloud.sqlcommenter.flask.middleware import SqlCommenterMiddleware
7
8app = Flask(__name__)
9app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:pass@localhost/dbname'
10
11# 1. Initialize the database
12db = SQLAlchemy(app)
13
14# 2. Wrap the Flask application with the SqlCommenterMiddleware
15app.wsgi_app = SqlCommenterMiddleware(app.wsgi_app)
16
17@app.route('/')
18def index():
19    # When this query executes, sqlcommenter will append comments like:
20    # /*controller='index',route='/',framework='flask'*/
21    users = db.session.execute(db.select(User)).all()
22    return "Query executed with sqlcommenter tags!"
23
24if __name__ == "__main__":
25    app.run()