繁体   English   中英

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

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

我正在尝试实现此代码https://gist.github.com/1859653 ,它允许sqlalchemy与hstore列进行交互。

它在gist的评论中提到需要运行psycopg2.extras.register_hstore。 什么时候应该运行这个功能? 如果我做:

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

heroku错误与'太多连接'

还提到使用pghstore(http://pypi.python.org/pypi/pghstore)而不是psycopg2,但它没有说明如何设置它。

另外,我想知道这个附加代码是否支持使用hstore索引。

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

此外,SQLAlchemy 0.8+内置了HSTORE类型支持。

尝试这个:

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)

另见:

暂无
暂无

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

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