本文整理匯總了Python中aiomysql.create_pool方法的典型用法代碼示例。如果您正苦於以下問題:Python aiomysql.create_pool方法的具體用法?Python aiomysql.create_pool怎麽用?Python aiomysql.create_pool使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類aiomysql
的用法示例。
在下文中一共展示了aiomysql.create_pool方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: init
# 需要導入模塊: import aiomysql [as 別名]
# 或者: from aiomysql import create_pool [as 別名]
def init(cls, loop, **kwargs):
logging.info('aiomysql.create_pool start')
global dbPool
dbPool = await aiomysql.create_pool(
host=kwargs.get('host', 'localhost'),
port=kwargs.get('port', 3306),
user=kwargs['user'],
password=kwargs['password'],
db=kwargs['db'],
charset=kwargs.get('charset', 'utf8'),
autocommit=kwargs.get('autocommit', True),
maxsize=kwargs.get('maxsize', 10),
minsize=kwargs.get('minsize', 1),
loop=loop
)
logging.info('aiomysql.create_pool end')
return dbPool
示例2: __aenter__
# 需要導入模塊: import aiomysql [as 別名]
# 或者: from aiomysql import create_pool [as 別名]
def __aenter__(self) -> "MySQLSource":
# Verify MySQL connection using provided certificate, if given
ssl_ctx = None
if self.config.ca is not None:
self.logger.debug(
f"Secure connection to MySQL: CA file: {self.config.ca}"
)
ssl_ctx = ssl.create_default_context(cafile=self.config.ca)
else:
self.logger.critical("Insecure connection to MySQL")
# Connect to MySQL
self.pool = await aiomysql.create_pool(
host=self.config.host,
port=self.config.port,
user=self.config.user,
password=self.config.password,
db=self.config.db,
ssl=ssl_ctx,
)
self.__db = self.pool.acquire()
self.db = await self.__db.__aenter__()
return self
示例3: __aenter__
# 需要導入模塊: import aiomysql [as 別名]
# 或者: from aiomysql import create_pool [as 別名]
def __aenter__(self) -> "MySQLDatabase":
# Verify MySQL connection using provided certificate, if given
ssl_ctx = None
if self.config.ca is not None:
self.logger.debug(
f"Secure connection to MySQL: CA file: {self.config.ca}"
)
ssl_ctx = ssl.create_default_context(cafile=self.config.ca)
else:
self.logger.critical("Insecure connection to MySQL")
# Connect to MySQL
self.pool = await aiomysql.create_pool(
host=self.config.host,
port=self.config.port,
user=self.config.user,
password=self.config.password,
db=self.config.db,
ssl=ssl_ctx,
)
self.__db = self.pool.acquire()
self.db = await self.__db.__aenter__()
return self
示例4: create_pool
# 需要導入模塊: import aiomysql [as 別名]
# 或者: from aiomysql import create_pool [as 別名]
def create_pool(loop, user, password, db, **kw):
# 該函數用於創建連接池
global __pool
__pool = await aiomysql.create_pool(
loop=loop, # 傳遞消息循環對象loop用於異步執行
user=user, # user是通過關鍵字參數傳進來的
password=password, # 密碼也是通過關鍵字參數傳進來的
db=db, # 數據庫名字
host=kw.get('host', 'localhost'), # 默認定義host名字為localhost
port=kw.get('port', 3306), # 默認定義mysql的默認端口是3306
charset=kw.get('charset', 'utf8'), # 默認數據庫字符集是utf8
autocommit=kw.get('autocommit', True), # 默認自動提交事務
maxsize=kw.get('maxsize', 10), # 連接池最多同時處理10個請求
minsize=kw.get('minsize', 1) # 連接池最少1個請求
)
# 用於SQL的SELECT語句。對應select方法,傳入sql語句和參數
示例5: select
# 需要導入模塊: import aiomysql [as 別名]
# 或者: from aiomysql import create_pool [as 別名]
def select(sql, args, size=None):
log(sql, args)
# 聲明全局變量,這樣才能引用create_pool函數創建的__pool變量
global __pool
# 從連接池中獲得一個數據庫連接
# 用with語句可以封裝清理(關閉conn)和處理異常工作
async with __pool.get() as conn:
# 等待連接對象返回DictCursor可以通過dict的方式獲取數據庫對象,需要通過遊標對象執行SQL
async with conn.cursor(aiomysql.DictCursor) as cur:
# 設置執行語句,其中sql語句的占位符為?,而python為%s, 這裏要做一下替換
# args是sql語句的參數
await cur.execute(sql.replace('?', '%s'), args or ())
# 如果製定了查詢數量,則查詢製定數量的結果,如果不指定則查詢所有結果
if size:
rs = await cur.fetchmany(size) # 從數據庫獲取指定的行數
else:
rs = await cur.fetchall() # 返回所有結果集
logging.info("返回的行數:%s" % len(rs))
return rs # 返回結果集
# 定義execute()函數執行insert update delete語句
示例6: start
# 需要導入模塊: import aiomysql [as 別名]
# 或者: from aiomysql import create_pool [as 別名]
def start(self, _app, loop):
_k = dict(loop=loop)
if self.config:
config = self.config
else:
config = _app.config.get('MYSQL')
_k.update(config)
_mysql = await create_pool(**_k)
log.info('opening mysql connection for [pid:{}]'.format(os.getpid()))
async def _query(sqlstr, args=None):
async with _mysql.acquire() as conn:
async with conn.cursor() as cur:
final_str = cur.mogrify(sqlstr, args)
log.info('mysql query [{}]'.format(final_str))
await cur.execute(final_str)
value = await cur.fetchall()
return value
setattr(_mysql, 'query', _query)
_app.mysql = _mysql
示例7: test_example
# 需要導入模塊: import aiomysql [as 別名]
# 或者: from aiomysql import create_pool [as 別名]
def test_example():
pool = yield from aiomysql.create_pool(
host='127.0.0.1',
port=3306,
user='root',
password='',
db='mysql',
loop=loop
)
with (yield from pool) as conn:
cur = yield from conn.cursor()
yield from cur.execute("SELECT 10")
# print(cur.description)
(r,) = yield from cur.fetchone()
assert r == 10
pool.close()
yield from pool.wait_closed()
示例8: test_create_pool_deprecations
# 需要導入模塊: import aiomysql [as 別名]
# 或者: from aiomysql import create_pool [as 別名]
def test_create_pool_deprecations(mysql_params, loop):
async with create_pool(loop=loop, **mysql_params) as pool:
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
async with pool.get() as conn:
pass
# The first warning emitted is expected to be DeprecationWarning:
# in the past, we used to check for the last one but this assumption
# breaks under Python 3.7 that also emits a `ResourceWarning` when
# executed with `PYTHONASYNCIODEBUG=1`.
assert issubclass(w[0].category, DeprecationWarning)
assert conn.closed
async with create_pool(loop=loop, **mysql_params) as pool:
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
with await pool as conn:
pass
assert issubclass(w[-1].category, DeprecationWarning)
assert conn.closed
示例9: pool_creator
# 需要導入模塊: import aiomysql [as 別名]
# 或者: from aiomysql import create_pool [as 別名]
def pool_creator(mysql_params, loop):
pools = []
@asyncio.coroutine
def f(**kw):
conn_kw = mysql_params.copy()
conn_kw.update(kw)
_loop = conn_kw.pop('loop', loop)
pool = yield from aiomysql.create_pool(loop=_loop, **conn_kw)
pools.append(pool)
return pool
yield f
for pool in pools:
pool.close()
loop.run_until_complete(pool.wait_closed())
示例10: test_auth_plugin_renegotiation
# 需要導入模塊: import aiomysql [as 別名]
# 或者: from aiomysql import create_pool [as 別名]
def test_auth_plugin_renegotiation(mysql_server, loop):
async with create_pool(**mysql_server['conn_params'],
auth_plugin='mysql_clear_password',
loop=loop) as pool:
async with pool.get() as conn:
async with conn.cursor() as cur:
# Run simple command
await cur.execute("SHOW DATABASES;")
value = await cur.fetchall()
assert len(value), 'No databases found'
# Check we tried to use the cleartext plugin
assert conn._client_auth_plugin == 'mysql_clear_password', \
'Client did not try clear password auth'
# Check the server asked us to use MySQL's default plugin
assert conn._server_auth_plugin in (
'mysql_native_password', 'caching_sha2_password'), \
'Server did not ask for native auth'
# Check we actually used the servers default plugin
assert conn._auth_plugin_used in (
'mysql_native_password', 'caching_sha2_password'), \
'Client did not renegotiate with server\'s default auth'
示例11: go
# 需要導入模塊: import aiomysql [as 別名]
# 或者: from aiomysql import create_pool [as 別名]
def go():
async with create_pool(host=MYSQL_HOST, port=3306,
user=MYSQL_USER, password=MYSQL_PASS,
db='mysql', loop=loop) as pool:
async with pool.get() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT 42;")
value = await cur.fetchone()
print(value)
示例12: __aenter__
# 需要導入模塊: import aiomysql [as 別名]
# 或者: from aiomysql import create_pool [as 別名]
def __aenter__(self) -> "DemoAppSource":
self.pool = await aiomysql.create_pool(
host=self.config.host,
port=self.config.port,
user=self.config.user,
password=self.config.password,
db=self.config.db,
)
self.__db = self.pool.acquire()
self.db = await self.__db.__aenter__()
return self
示例13: connect
# 需要導入模塊: import aiomysql [as 別名]
# 或者: from aiomysql import create_pool [as 別名]
def connect(self):
"""Create connection pool asynchronously.
"""
self.pool = await aiopg.create_pool(
loop=self.loop,
timeout=self.timeout,
database=self.database,
**self.connect_params)
示例14: _connect
# 需要導入模塊: import aiomysql [as 別名]
# 或者: from aiomysql import create_pool [as 別名]
def _connect(self, database, **kwargs):
if not mysql:
raise ImproperlyConfigured('MySQLdb or PyMySQL must be installed.')
conn_kwargs = {
'charset': 'utf8',
'use_unicode': True,
}
conn_kwargs.update(kwargs)
return await aiomysql.create_pool(db=database, **conn_kwargs)
示例15: create_pool
# 需要導入模塊: import aiomysql [as 別名]
# 或者: from aiomysql import create_pool [as 別名]
def create_pool(loop, **kw):
logging.info('創建連接池...')
# 聲明變量__pool是一個全局變量,如果不加聲明,__pool就會被默認為一個私有變量,不能被其他函數引用
global __pool
# 調用一個自協程來創建全局連接池,create_pool的返回值是一個pool實例對象
__pool = await aiomysql.create_pool(
# 下麵就是創建數據庫連接需要用到的一些參數,從**kw(關鍵字參數)中取出來
# kw.get的作用應該是,當沒有傳入參數是,默認參數就是get函數的第二項
host=kw.get('host', 'localhost'), # 數據庫服務器位置,默認設在本地
port=kw.get('port', 3306), # mysql的端口,默認設為3306
user=kw['user'], # 登陸用戶名,通過關鍵詞參數傳進來。
password=kw['password'], # 登陸密碼,通過關鍵詞參數傳進來
db=kw['db'], # 當前數據庫名
charset=kw.get('charset', 'utf8'), # 設置編碼格式,默認為utf-8
autocommit=kw.get('autocommit', True), # 自動提交模式,設置默認開啟
maxsize=kw.get('maxsize', 10), # 最大連接數默認設為10
minsize=kw.get('minsize', 1), # 最小連接數,默認設為1,這樣可以保證任何時候都會有一個數據庫連接
loop=loop # 傳遞消息循環對象,用於異步執行
)
# =================================以下是SQL函數處理區====================================
# select和execute方法是實現其他Model類中SQL語句都經常要用的方法
# 將執行SQL的代碼封裝僅select函數,調用的時候隻要傳入sql,和sql所需要的一些參數就好
# sql參數即為sql語句,args表示要搜索的參數
# size用於指定最大的查詢數量,不指定將返回所有查詢結果