-
Hi. Here is a simplified example of an application opening and closing a database connection before and after each request, and using a custom converter to handle database objects. from flask import Flask
from flask import g
from werkzeug.routing import BaseConverter
app = Flask(__name__)
class FoobarConverter(BaseConverter):
def to_url(self, obj):
return obj.id
app.logger.warning("converter.to_url")
def to_python(self, id):
app.logger.warning("converter.to_python")
return g.db.query_object_from(id)
app.url_map.converters["foobar"] = FoobarConverter
@app.before_request
def before_app_request():
app.logger.warning("before_request")
g.db = open_db_connection()
@app.after_request
def after_request(response):
app.logger.warning("after_request")
if "db" in g:
g.db.close_connection()
return response
@app.route("/<foobar:foobar>")
def index(foobar):
return f"Hello {foobar.name}"
if __name__ == "__main__":
app.run() According to the logs I see that the Though this feels strange to me, any thoughts? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
That's fine. It's essentially what happens with Flask-SQLAlchemy, although there it's more hidden. The connection isn't made until you actually access the database with something like |
Beta Was this translation helpful? Give feedback.
That's fine.
It's essentially what happens with Flask-SQLAlchemy, although there it's more hidden. The connection isn't made until you actually access the database with something like
db.session.execute()
, then it's reused.