简体   繁体   English

如何使用带有flask-sqlalchemy的Postgres'Hstore列?

[英]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. 我正在尝试实现此代码https://gist.github.com/1859653 ,它允许sqlalchemy与hstore列进行交互。

Its mentioned in that gist's comments the need to run the psycopg2.extras.register_hstore. 它在gist的评论中提到需要运行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' heroku错误与'太多连接'

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. 还提到使用pghstore(http://pypi.python.org/pypi/pghstore)而不是psycopg2,但它没有说明如何设置它。

Also, I'm wondering if the use of hstore indexes is supported in this add-on code. 另外,我想知道这个附加代码是否支持使用hstore索引。

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. 从SQLAlchemy 0.8开始,PostgreSQL的psycopg2连接器(默认情况下) 默认注册hstore扩展 ,并且不再需要apply_driver_hacks解决方法。

Also, SQLAlchemy 0.8+ has builtin HSTORE type support. 此外,SQLAlchemy 0.8+内置了HSTORE类型支持。

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: 另见:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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