本文整理汇总了Python中asyncpg.connect方法的典型用法代码示例。如果您正苦于以下问题:Python asyncpg.connect方法的具体用法?Python asyncpg.connect怎么用?Python asyncpg.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncpg
的用法示例。
在下文中一共展示了asyncpg.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: connect
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import connect [as 别名]
def connect(self, loop=None, **kwargs):
conn_info = self.get_connection_spec()
conn_info.update(kwargs)
conn = await asyncpg.connect(loop=loop, **conn_info)
if (not kwargs.get('user')
and self._default_session_auth
and conn_info.get('user') != self._default_session_auth):
# No explicit user given, and the default
# SESSION AUTHORIZATION is different from the user
# used to connect.
await conn.execute(
f'SET SESSION AUTHORIZATION {self._default_session_auth};'
)
return conn
示例2: __aenter__
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import connect [as 别名]
def __aenter__(self) -> PgRenderLocker:
# pg_connection: asyncpg, not Django database, because we use its
# transaction asynchronously. (Async is so much easier than threading.)
pg_config = settings.DATABASES["default"]
pg_connection = await asyncpg.connect(
host=pg_config["HOST"],
user=pg_config["USER"],
password=pg_config["PASSWORD"],
database=pg_config["NAME"],
port=pg_config["PORT"],
timeout=pg_config["CONN_MAX_AGE"],
command_timeout=pg_config["CONN_MAX_AGE"],
)
self.pg_connection = pg_connection
loop = asyncio.get_event_loop()
interval = pg_config["CONN_MAX_AGE"]
self.heartbeat_task = loop.create_task(
self.send_pg_heartbeats_forever(interval)
)
return self
示例3: test_auth_password_cleartext_callable
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import connect [as 别名]
def test_auth_password_cleartext_callable(self):
def get_correctpassword():
return 'correctpassword'
def get_wrongpassword():
return 'wrongpassword'
conn = await self.connect(
user='password_user',
password=get_correctpassword)
await conn.close()
with self.assertRaisesRegex(
asyncpg.InvalidPasswordError,
'password authentication failed for user "password_user"'):
await self._try_connect(
user='password_user',
password=get_wrongpassword)
示例4: test_auth_password_cleartext_callable_coroutine
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import connect [as 别名]
def test_auth_password_cleartext_callable_coroutine(self):
async def get_correctpassword():
return 'correctpassword'
async def get_wrongpassword():
return 'wrongpassword'
conn = await self.connect(
user='password_user',
password=get_correctpassword)
await conn.close()
with self.assertRaisesRegex(
asyncpg.InvalidPasswordError,
'password authentication failed for user "password_user"'):
await self._try_connect(
user='password_user',
password=get_wrongpassword)
示例5: test_ssl_connection_custom_context
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import connect [as 别名]
def test_ssl_connection_custom_context(self):
ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ssl_context.load_verify_locations(SSL_CA_CERT_FILE)
con = await self.connect(
host='localhost',
user='ssl_user',
ssl=ssl_context)
try:
self.assertEqual(await con.fetchval('SELECT 42'), 42)
with self.assertRaises(asyncio.TimeoutError):
await con.execute('SELECT pg_sleep(5)', timeout=0.5)
self.assertEqual(await con.fetchval('SELECT 43'), 43)
finally:
await con.close()
示例6: test_find_tables
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import connect [as 别名]
def test_find_tables(self):
tables = importer.find_tables(test_dir / '../testlayers/testmaptiles.yaml')
self.assertEqual(tables, ['osm_housenumber_point'])
# async def test_pg_func(self):
# conn = None
# try:
# pghost, pgport, dbname, user, password = parse_pg_args(
# dict(args=dict(dict=lambda v: None))
# )
# conn = await asyncpg.connect(
# database=dbname, host=pghost, port=pgport, user=user, password=password,
# )
# PgWarnings(conn)
# await conn.set_builtin_type_codec('hstore', codec_name='pg_contrib.hstore')
#
# finally:
# if conn:
# await conn.close()
示例7: DBClient
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import connect [as 别名]
def DBClient():
return await asyncpg.connect(
user=DBUSER,
password=DBPASSWORD,
database=DBNAME,
host=DBHOST,
port=DBPORT,
)
示例8: _test_connection
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import connect [as 别名]
def _test_connection(self, timeout=60):
self._connection_addr = None
loop = asyncio.new_event_loop()
try:
for _ in range(timeout):
if self._connection_addr is None:
conn_addr = self._get_connection_addr()
if conn_addr is None:
time.sleep(1)
continue
try:
con = loop.run_until_complete(
asyncpg.connect(database='postgres',
user='postgres',
timeout=5,
loop=loop,
host=self._connection_addr[0],
port=self._connection_addr[1]))
except (OSError, asyncio.TimeoutError,
asyncpg.CannotConnectNowError,
asyncpg.PostgresConnectionError):
time.sleep(1)
continue
except asyncpg.PostgresError:
# Any other error other than ServerNotReadyError or
# ConnectionError is interpreted to indicate the server is
# up.
break
else:
loop.run_until_complete(con.close())
break
finally:
loop.close()
return 'running'
示例9: get_remote_pg_cluster
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import connect [as 别名]
def get_remote_pg_cluster(dsn: str) -> RemoteCluster:
addrs, params = pgconnparams.parse_dsn(dsn)
if len(addrs) > 1:
raise ValueError('multiple hosts in Postgres DSN are not supported')
rcluster = RemoteCluster(addrs[0], params)
loop = asyncio.new_event_loop()
async def _is_rds():
conn = await rcluster.connect()
try:
rds_super = await conn.fetch(
"SELECT * FROM pg_roles WHERE rolname = 'rds_superuser'"
)
finally:
await conn.close()
return bool(rds_super)
try:
is_rds = loop.run_until_complete(_is_rds())
finally:
loop.close()
if is_rds:
return RDSCluster(addrs[0], params)
else:
return rcluster
示例10: new_connection
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import connect [as 别名]
def new_connection(self):
con_args = self._connect_args.copy()
con_args['database'] = self._dbname
try:
return await asyncpg.connect(**con_args)
except asyncpg.InvalidCatalogNameError as ex:
raise errors.AuthenticationError(str(ex)) from ex
except Exception as ex:
raise errors.InternalServerError(str(ex)) from ex
示例11: connect
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import connect [as 别名]
def connect(
self,
dbname: str,
dbver: bytes
) -> CompilerDatabaseState:
self._dbname = dbname
self._cached_db = None
await self._get_database(dbver)
示例12: collect_postgres_stats
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import connect [as 别名]
def collect_postgres_stats(self, ident: str, vacuum_full: bool = True):
creds = self.postgres_creds
conn = await asyncpg.connect(
host=self.internal_host,
port="5432",
user=creds["admin_account"],
password=creds["admin_password"],
database=self.wallet_name,
)
tables = ("items", "tags_encrypted", "tags_plaintext")
for t in tables:
await conn.execute(f"VACUUM FULL {t}" if vacuum_full else f"VACUUM {t}")
sizes = await conn.fetch(
"""
SELECT relname AS "relation",
pg_size_pretty(pg_total_relation_size(C.oid)) AS "total_size"
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE nspname = 'public'
ORDER BY pg_total_relation_size(C.oid) DESC;
"""
)
results = {k: [0, "0B"] for k in tables}
for row in sizes:
if row["relation"] in results:
results[row["relation"]][1] = row["total_size"].replace(" ", "")
for t in tables:
row = await conn.fetchrow(f"""SELECT COUNT(*) AS "count" FROM {t}""")
results[t][0] = row["count"]
self.wallet_stats.append((ident, results))
await conn.close()
示例13: _execute_pg_query
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import connect [as 别名]
def _execute_pg_query(url, query):
conn = await asyncpg.connect(url)
if callable(query):
await query(conn)
else:
await conn.execute(query)
await conn.close()
示例14: asyncpg_init
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import connect [as 别名]
def asyncpg_init(db_uri):
import asyncpg
async def create_conn():
global asyncpg_conn
asyncpg_conn = await asyncpg.connect(db_uri)
async_run(create_conn)
# asyncpg_init(config.DATABASE_URI)
示例15: setUpClass
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import connect [as 别名]
def setUpClass(cls):
super().setUpClass()
cls._connection = None
cls._cursor = None
cls._tracer = cls.tracer_provider.get_tracer(__name__)
AsyncPGInstrumentor().instrument(tracer_provider=cls.tracer_provider)
cls._connection = _await(
asyncpg.connect(
database=POSTGRES_DB_NAME,
user=POSTGRES_USER,
password=POSTGRES_PASSWORD,
host=POSTGRES_HOST,
port=POSTGRES_PORT,
)
)