简体   繁体   中英

How to use Postgres' Hstore column with flask-sqlalchemy?

I am attempting to implement this code https://gist.github.com/1859653 that allows sqlalchemy to interact with an hstore column.

Its mentioned in that gist's comments the need to run the psycopg2.extras.register_hstore. When and were should this function be run? If i do:

@app.before_request
def reg_hstore() :
register_hstore(db.engine.raw_connection(), True)

heroku errors with 'too many connections'

there is also mention of using pghstore (http://pypi.python.org/pypi/pghstore) instead of psycopg2 but it gives no indication how to set it up.

Also, I'm wondering if the use of hstore indexes is supported in this add-on code.

Since SQLAlchemy 0.8, psycopg2 connector for PostgreSQL (which is default) will register hstore extension by default and the apply_driver_hacks workaround is not needed anymore.

Also, SQLAlchemy 0.8+ has builtin HSTORE type support.

Try this:

from flaskext.sqlalchemy import SQLAlchemy
import psycopg2
import psycopg2.extras

class _SQLAlchemy(SQLAlchemy):
    def apply_driver_hacks(self, app, info, options):
        """This method adds option to support hstore on psycopg2"""

        if info.drivername == "postgres":
            def _connect():
                conn = psycopg2.connect(user=info.username,
                                        host=info.host,
                                        port=info.port,
                                        dbname=info.database,
                                        password=info.password)
                psycopg2.extras.register_hstore(conn)
                return conn
            options["creator"] = _connect
        SQLAlchemy.apply_driver_hacks(self, app, info, options)

Also see:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM