本文整理汇总了Python中psycopg2.extras.register_hstore函数的典型用法代码示例。如果您正苦于以下问题:Python register_hstore函数的具体用法?Python register_hstore怎么用?Python register_hstore使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了register_hstore函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: register_type_handlers
def register_type_handlers(connection, **kwargs):
if connection.vendor != 'postgresql':
return
try:
oids, array_oids = get_hstore_oids(connection.alias)
register_hstore(connection.connection, globally=True, oid=oids, array_oid=array_oids)
except ProgrammingError:
# Hstore is not available on the database.
#
# If someone tries to create an hstore field it will error there.
# This is necessary as someone may be using PSQL without extensions
# installed but be using other features of contrib.postgres.
#
# This is also needed in order to create the connection in order to
# install the hstore extension.
pass
try:
citext_oids = get_citext_oids(connection.alias)
array_type = psycopg2.extensions.new_array_type(citext_oids, 'citext[]', psycopg2.STRING)
psycopg2.extensions.register_type(array_type, None)
except ProgrammingError:
# citext is not available on the database.
#
# The same comments in the except block of the above call to
# register_hstore() also apply here.
pass
开发者ID:quanpower,项目名称:django,代码行数:28,代码来源:signals.py
示例2: test_array_cast
def test_array_cast(self):
from psycopg2.extras import register_hstore
register_hstore(self.conn)
cur = self.conn.cursor()
cur.execute("select array['a=>1'::hstore, 'b=>2'::hstore];")
a = cur.fetchone()[0]
self.assertEqual(a, [{'a': '1'}, {'b': '2'}])
开发者ID:smira,项目名称:psycopg2-ctypes,代码行数:7,代码来源:test_types_extras.py
示例3: register_type_handlers
def register_type_handlers(connection, **kwargs):
if connection.vendor != 'postgresql':
return
try:
register_hstore(connection.connection, globally=True)
except ProgrammingError:
# Hstore is not available on the database.
#
# If someone tries to create an hstore field it will error there.
# This is necessary as someone may be using PSQL without extensions
# installed but be using other features of contrib.postgres.
#
# This is also needed in order to create the connection in order to
# install the hstore extension.
pass
try:
with connection.cursor() as cursor:
# Retrieve oids of citext arrays.
cursor.execute("SELECT typarray FROM pg_type WHERE typname = 'citext'")
oids = tuple(row[0] for row in cursor)
array_type = psycopg2.extensions.new_array_type(oids, 'citext[]', psycopg2.STRING)
psycopg2.extensions.register_type(array_type, None)
except ProgrammingError:
# citext is not available on the database.
#
# The same comments in the except block of the above call to
# register_hstore() also apply here.
pass
开发者ID:KIKUYA-Takumi,项目名称:django,代码行数:30,代码来源:signals.py
示例4: test_roundtrip
def test_roundtrip(self):
from psycopg2.extras import register_hstore
register_hstore(self.conn)
cur = self.conn.cursor()
def ok(d):
cur.execute("select %s", (d,))
d1 = cur.fetchone()[0]
self.assertEqual(len(d), len(d1))
for k in d:
self.assert_(k in d1, k)
self.assertEqual(d[k], d1[k])
ok({})
ok({"a": "b", "c": None})
ab = map(chr, range(32, 128))
ok(dict(zip(ab, ab)))
ok({"".join(ab): "".join(ab)})
self.conn.set_client_encoding("latin1")
if sys.version_info[0] < 3:
ab = map(chr, range(32, 127) + range(160, 255))
else:
ab = bytes(range(32, 127) + range(160, 255)).decode("latin1")
ok({"".join(ab): "".join(ab)})
ok(dict(zip(ab, ab)))
开发者ID:hayalifabrika,项目名称:living-galapagos,代码行数:29,代码来源:test_types_extras.py
示例5: register_hstore_handler
def register_hstore_handler(connection, **kwargs):
if not connection.settings_dict.get('HAS_HSTORE', True):
return
if sys.version_info[0] < 3:
register_hstore(connection.connection, globally=True, unicode=True)
else:
register_hstore(connection.connection, globally=True)
开发者ID:Geekfish,项目名称:djorm-ext-hstore,代码行数:7,代码来源:models.py
示例6: test_roundtrip_array
def test_roundtrip_array(self):
from psycopg2.extras import register_hstore
register_hstore(self.conn)
ds = []
ds.append({})
ds.append({"a": "b", "c": None})
ab = map(chr, range(32, 128))
ds.append(dict(zip(ab, ab)))
ds.append({"".join(ab): "".join(ab)})
self.conn.set_client_encoding("latin1")
if sys.version_info[0] < 3:
ab = map(chr, range(32, 127) + range(160, 255))
else:
ab = bytes(range(32, 127) + range(160, 255)).decode("latin1")
ds.append({"".join(ab): "".join(ab)})
ds.append(dict(zip(ab, ab)))
cur = self.conn.cursor()
cur.execute("select %s", (ds,))
ds1 = cur.fetchone()[0]
self.assertEqual(ds, ds1)
开发者ID:hayalifabrika,项目名称:living-galapagos,代码行数:26,代码来源:test_types_extras.py
示例7: connect
def connect(dsn=None, *, timeout=TIMEOUT, loop=None,
enable_json=True, enable_hstore=True, echo=False, **kwargs):
"""A factory for connecting to PostgreSQL.
The coroutine accepts all parameters that psycopg2.connect() does
plus optional keyword-only `loop` and `timeout` parameters.
Returns instantiated Connection object.
"""
if loop is None:
loop = asyncio.get_event_loop()
waiter = asyncio.Future(loop=loop)
conn = Connection(dsn, loop, timeout, waiter, bool(echo), **kwargs)
try:
yield from conn._poll(waiter, timeout)
except Exception:
conn.close()
raise
if enable_json:
extras.register_default_json(conn._conn)
if enable_hstore:
oids = yield from _enable_hstore(conn)
if oids is not None:
oid, array_oid = oids
extras.register_hstore(conn._conn, oid=oid, array_oid=array_oid)
return conn
开发者ID:nerandell,项目名称:aiopg,代码行数:28,代码来源:connection.py
示例8: correct_qa_config
def correct_qa_config(cursor, branch_id, merge_base_commit_hash):
""" Return the config_id to release a new commit to this build with """
register_hstore(cursor)
# if there are releases on this branch, use the config from the most recent
# otherwise use the most recent release of the merge base commit
cursor.execute(
("select config_id "
" from release "
" join iteration using (iteration_id) "
" where branch_id=%s "
" or commit_hash=%s "
" order by iteration.created_dt desc, release.created_dt desc "
" limit 1 "),
(branch_id, merge_base_commit_hash),
)
results = cursor.fetchall()
if len(results) is 0:
config_id = save(
cursor,
'config', # table
['key_value_pairs'], # unique columns
['key_value_pairs'], # column
({},), # value
)
elif len(results) is 1:
config_id = results[0][0]
else:
raise ValueError("There should only be one correct config")
return config_id
开发者ID:OAODEV,项目名称:herd-service,代码行数:29,代码来源:handlers.py
示例9: __init__
def __init__(self, engine, **kw):
super(HStore, self).__init__(engine, **kw)
spliturl = urlsplit(engine)
try:
self._conn = conn = psycopg2.connect(
host=spliturl.hostname,
port=spliturl.port,
database=spliturl.path,
user=spliturl.username or "",
password=spliturl.password or "",
)
self._store = db = conn.cursor(cursor_factory=extras.RealDictCursor)
except psycopg2.OperationalError:
logging.exception("configuration error")
raise TypeError("configuration error")
try:
db.execute("CREATE EXTENSION hstore")
conn.commit()
except psycopg2.ProgrammingError:
conn.rollback()
extras.register_hstore(conn)
try:
db.execute("CREATE TABLE shove (id serial PRIMARY KEY, data hstore)")
conn.commit()
db.execute("INSERT INTO shove (data) VALUES (%s)", ['"key"=>"value"'])
conn.commit()
db.execute("UPDATE shove SET data = delete(data, %s)", ["key"])
except psycopg2.ProgrammingError:
conn.rollback()
开发者ID:aie108,项目名称:Plex-Trakt-Scrobbler,代码行数:29,代码来源:hstore.py
示例10: on_connect
def on_connect(conn):
hstore_oids = self._hstore_oids(conn)
if hstore_oids is not None:
oid, array_oid = hstore_oids
if util.py2k:
extras.register_hstore(conn, oid=oid, array_oid=array_oid, unicode=True)
else:
extras.register_hstore(conn, oid=oid, array_oid=array_oid)
开发者ID:BobbyJoeSmith3,项目名称:swampr,代码行数:8,代码来源:psycopg2.py
示例11: setup_postgresql_hstore_extension
def setup_postgresql_hstore_extension(sender, connection, **kwargs):
from psycopg2.extras import register_hstore
cursor = connection.connection.cursor()
cursor.execute('CREATE EXTENSION IF NOT EXISTS hstore')
if PY2:
register_hstore(connection.connection, globally=True, unicode=True)
else:
register_hstore(connection.connection, globally=True)
开发者ID:tonysepia,项目名称:pytoolbox,代码行数:8,代码来源:handlers.py
示例12: _register_hstore_converter
def _register_hstore_converter(self, engine):
from psycopg2.extras import register_hstore
from psycopg2 import ProgrammingError
connection = engine.connect()
try:
register_hstore(connection.connection, globally=True)
except ProgrammingError:
pass
开发者ID:esho,项目名称:spire,代码行数:9,代码来源:dialect.py
示例13: renderTile
def renderTile(self, width, height, srs, coord):
""" Render a single tile, return a SaveableResponse instance.
"""
# tilesize = self.tileSize * 16
#
# # center pixel on zoomlevel
# center = (tilesize << coord.zoom) >> 1
# # maximum coordinate in web mercator
# f900913 = 20037508.342789244
#
# # pixel relative to global center
# dx = (coord.column * tilesize) - center
# # flip y-axis
# dy = center - (coord.row * tilesize)
#
# # size of one pixel
# div = f900913 / center
#
conn = _connect(self.dbdsn)
db = conn.cursor()
register_hstore(conn, True, False)
db.execute(self.query_tile, (coord.column * self.tileSize, coord.row * self.tileSize, coord.zoom))
rows = db.fetchall()
logging.debug(self.query_tile)
bbox = 0
tile = {"bbox": bbox, "granularity":10000, "features":[]}
features = []
for row in rows:
# empty geometry
if (row[0] is None) or (row[1] is None):
continue
#logging.debug(str(row[1]))
geojson = json.loads(str(row[1]))
# tags = {}
# for tag in row[0].iteritems():
# tags[tag[0]] = ("%s" %(tag[1])).decode('utf-8')
#
# print tags
#
# geojson["properties"] = tags
geojson["properties"] = row[0]
features.append(geojson)
tile["features"].extend(features)
try:
conn.commit()
except Exception, e:
logging.error(">>> %s", e)
conn.rollback()
开发者ID:quake4ialdaris,项目名称:TileStache,代码行数:57,代码来源:__init__.py
示例14: on_connect
def on_connect(conn):
hstore_oids = self._hstore_oids(conn)
if hstore_oids is not None:
oid, array_oid = hstore_oids
kw = {'oid': oid}
if util.py2k:
kw['unicode'] = True
if self.psycopg2_version >= (2, 4, 3):
kw['array_oid'] = array_oid
extras.register_hstore(conn, **kw)
开发者ID:Althea-Lobo,项目名称:Flask-Skeleton,代码行数:10,代码来源:psycopg2.py
示例15: _cursor
def _cursor(self):
# ensure that we're connected
cursor = super(DatabaseWrapper, self)._cursor()
# register hstore extension
register_hstore(self.connection, globally=True, unicode=True)
# bypass future registrations
self._cursor = super(DatabaseWrapper, self)._cursor
return cursor
开发者ID:popen2,项目名称:django-hstore,代码行数:10,代码来源:base.py
示例16: test_register_curs
def test_register_curs(self):
from psycopg2.extras import register_hstore
cur = self.conn.cursor()
register_hstore(cur)
cur.execute("select null::hstore, ''::hstore, 'a => b'::hstore")
t = cur.fetchone()
self.assert_(t[0] is None)
self.assertEqual(t[1], {})
self.assertEqual(t[2], {"a": "b"})
开发者ID:hayalifabrika,项目名称:living-galapagos,代码行数:10,代码来源:test_types_extras.py
示例17: get_tasks_from_db
def get_tasks_from_db(args):
db_user = args.user
if not args.user:
db_user = getpass.getuser()
db_name = args.database
if not args.database:
db_name = 'osm'
db_schema = args.schema
if not args.schema:
db_schema = 'osmosis'
db_pass = args.password
if not args.password:
db_pass = getpass.getpass('please enter the password for database {dbname} and user {dbuser}: '.format(dbname=db_name, dbuser=db_user))
db_query = args.query
db_string = "dbname={db_name} user={db_user} password={db_pass}".format(db_name=db_name,
db_user=db_user,
db_pass=db_pass,
)
if args.host:
db_string += " host={db_host}".format(db_host=args.host)
# open a connection, get a cursor
conn = psycopg2.connect(db_string)
cur = conn.cursor(cursor_factory=DictCursor)
if db_schema == 'osmosis':
# hstore is only default in osmosis schema
register_hstore(cur)
# get our results
cur.execute(db_query)
nodes = cur.fetchall()
for node in nodes:
osmid = node.get("id")
geom = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {"osmid": osmid},
"geometry": json.loads(geojson.dumps(
wkb.loads(node["geom"].decode("hex"))))
}]
}
yield prepare_task(node=node,
args=args,
osmid=osmid,
geom=geom
)
开发者ID:grischard,项目名称:maproulette-loader,代码行数:55,代码来源:loader.py
示例18: register_hstore_on_connection_creation
def register_hstore_on_connection_creation(connection, sender, *args, **kwargs):
dbname = connection.alias
if dbname not in _oids:
oids1, oids2 = HstoreAdapter.get_oids(connection.connection)
if not oids1 and not oids2:
raise DatabaseError("hstore isn't installed on this database")
_oids[dbname] = (oids1[0], oids2[0])
oid, array_oid = _oids[dbname]
register_hstore(connection.connection, globally=True, oid=oid, array_oid=array_oid)
开发者ID:craigds,项目名称:hstore-field,代码行数:11,代码来源:fields.py
示例19: test_register_unicode
def test_register_unicode(self):
from psycopg2.extras import register_hstore
register_hstore(self.conn, unicode=True)
cur = self.conn.cursor()
cur.execute("select null::hstore, ''::hstore, 'a => b'::hstore")
t = cur.fetchone()
self.assert_(t[0] is None)
self.assertEqual(t[1], {})
self.assertEqual(t[2], {u"a": u"b"})
self.assert_(isinstance(t[2].keys()[0], unicode))
self.assert_(isinstance(t[2].values()[0], unicode))
开发者ID:hayalifabrika,项目名称:living-galapagos,代码行数:12,代码来源:test_types_extras.py
示例20: on_connect
def on_connect(conn):
hstore_oids = self._hstore_oids(conn)
if hstore_oids is not None:
oid, array_oid = hstore_oids
kw = {"oid": oid}
if util.py2k:
kw["unicode"] = True
if (
self.psycopg2_version
>= self.FEATURE_VERSION_MAP["array_oid"]
):
kw["array_oid"] = array_oid
extras.register_hstore(conn, **kw)
开发者ID:BY-jk,项目名称:sqlalchemy,代码行数:13,代码来源:psycopg2.py
注:本文中的psycopg2.extras.register_hstore函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论