1

I'm developing a web app with Flask-SQLAlchemy backed by a SQLite database. I need to call a method (create_collation) right after connecting. Without the SQLAlchemy framework, I can do that like this:

conn = sqlite3.connect(path)
conn.create_collation('my_collate', my_collate)
# ... go on and do fancy "order_by" stuff.

How do I do that in Flask-SQLAlchemy? Based on the API I was thinking of the following, but I get AttributeError: 'Engine' object has no attribute 'create_collation'.

from flask_sqlalchemy import SQLAlchemy

class MySQLAlchemy(SQLAlchemy):
    def create_engine(self, sa_url, engine_opts):
        engine = super().create_engine(sa_url, engine_opts)
        engine.create_collation('my_collate', self.my_collate)
        return engine

    @staticmethod
    def my_collate(string1, string2):
        return string1.locateCompare(string2)

Following the SQLAlchemy docs I think I need to get the connection rather than the engine. But I can't find out how.

Also, where should this go specifically in Flask-SQLAlchemy? What part ultimately "connect"s, and how do I tune into that?

1 Answer 1

3

SQLAlchemy has an Events API that allows you to create a function that will be called whenever the connection pool creates a new connection:

from sqlalchemy.event import listens_for
from sqlalchemy.pool import Pool

@listens_for(Pool, "connect")
def my_on_connect(dbapi_con, connection_record):
    dbapi_con.create_collation('my_collate', my_collate)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.