|
@@ -0,0 +1,93 @@
|
|
|
+"""
|
|
|
+@author: luojunhui
|
|
|
+"""
|
|
|
+import aiomysql
|
|
|
+
|
|
|
+from applications import log
|
|
|
+from config import env
|
|
|
+
|
|
|
+
|
|
|
+class AsyncMySQLClient(object):
|
|
|
+ """
|
|
|
+ Async MySQL
|
|
|
+ """
|
|
|
+
|
|
|
+ def __init__(self, app):
|
|
|
+ self.app = app
|
|
|
+
|
|
|
+ async def initPool(self):
|
|
|
+ """
|
|
|
+ 初始化连接
|
|
|
+ :return:
|
|
|
+ """
|
|
|
+ if env == "prod":
|
|
|
+ self.app.mysql_pool = await aiomysql.create_pool(
|
|
|
+ host='rm-bp1159bu17li9hi94.mysql.rds.aliyuncs.com',
|
|
|
+ port=3306,
|
|
|
+ user='crawler',
|
|
|
+ password='crawler123456@',
|
|
|
+ db='piaoquan-crawler',
|
|
|
+ charset='utf8mb4',
|
|
|
+ maxsize=100,
|
|
|
+ connect_timeout=120,
|
|
|
+ )
|
|
|
+ log(
|
|
|
+ code="1001",
|
|
|
+ env=env,
|
|
|
+ message="数据库初始化成功"
|
|
|
+ )
|
|
|
+ elif env == "dev":
|
|
|
+ self.app.mysql_pool = await aiomysql.create_pool(
|
|
|
+ host='rm-bp1159bu17li9hi94.mysql.rds.aliyuncs.com',
|
|
|
+ port=3306,
|
|
|
+ user='crawler',
|
|
|
+ password='crawler123456@',
|
|
|
+ db='piaoquan-crawler',
|
|
|
+ charset='utf8mb4',
|
|
|
+ maxsize=100,
|
|
|
+ connect_timeout=120,
|
|
|
+ )
|
|
|
+ log(
|
|
|
+ code="1001",
|
|
|
+ env=env,
|
|
|
+ message="数据库初始化成功"
|
|
|
+ )
|
|
|
+ else:
|
|
|
+ log(
|
|
|
+ code="1001",
|
|
|
+ env=env,
|
|
|
+ message="数据库初始化失败,环境校验失败"
|
|
|
+ )
|
|
|
+ return None
|
|
|
+
|
|
|
+ async def closePool(self):
|
|
|
+ """
|
|
|
+ 关闭 mysql 连接
|
|
|
+ :return:
|
|
|
+ """
|
|
|
+ self.app.mysql_pool.close()
|
|
|
+ await self.app.mysql_pool.wait_closed()
|
|
|
+
|
|
|
+ async def asyncSelect(self, sql):
|
|
|
+ """
|
|
|
+ select method
|
|
|
+ :param sql:
|
|
|
+ :return:
|
|
|
+ """
|
|
|
+ async with self.app.mysql_pool.acquire() as conn:
|
|
|
+ async with conn.cursor() as cursor:
|
|
|
+ await cursor.execute(sql)
|
|
|
+ result = await cursor.fetchall()
|
|
|
+ return result
|
|
|
+
|
|
|
+ async def asyncInsert(self, sql, params):
|
|
|
+ """
|
|
|
+ insert and update method
|
|
|
+ :param params:
|
|
|
+ :param sql:
|
|
|
+ :return:
|
|
|
+ """
|
|
|
+ async with self.app.mysql_pool.acquire() as coon:
|
|
|
+ async with coon.cursor() as cursor:
|
|
|
+ await cursor.execute(sql, params)
|
|
|
+ await coon.commit()
|