2022-04-24 14:35:13 +08:00
|
|
|
|
#!/usr/bin/env python
|
2023-09-03 22:34:05 +08:00
|
|
|
|
import os,time
|
2023-09-03 21:17:55 +08:00
|
|
|
|
import pysnooper
|
|
|
|
|
|
2022-05-13 20:47:22 +08:00
|
|
|
|
# @pysnooper.snoop()
|
2022-04-24 14:35:13 +08:00
|
|
|
|
def init_db():
|
2023-09-03 21:17:55 +08:00
|
|
|
|
SQLALCHEMY_DATABASE_URI = os.getenv('MYSQL_SERVICE', '')
|
2022-04-24 14:35:13 +08:00
|
|
|
|
if SQLALCHEMY_DATABASE_URI:
|
|
|
|
|
import sqlalchemy.engine.url as url
|
|
|
|
|
uri = url.make_url(SQLALCHEMY_DATABASE_URI)
|
|
|
|
|
"""Inits the Myapp application"""
|
|
|
|
|
import pymysql
|
|
|
|
|
# 创建连接
|
2023-09-03 22:34:05 +08:00
|
|
|
|
while True:
|
|
|
|
|
try:
|
|
|
|
|
# 创建连接
|
|
|
|
|
conn = pymysql.connect(host=uri.host, port=uri.port, user=uri.username, password=uri.password, charset='utf8')
|
|
|
|
|
break
|
|
|
|
|
except:
|
|
|
|
|
print('链接数据库失败,5s后重连', flush=True)
|
|
|
|
|
time.sleep(5)
|
2022-04-24 14:35:13 +08:00
|
|
|
|
# 创建游标
|
|
|
|
|
cursor = conn.cursor()
|
|
|
|
|
|
|
|
|
|
# 创建数据库的sql(如果数据库存在就不创建,防止异常)
|
2023-09-03 21:17:55 +08:00
|
|
|
|
sql = "CREATE DATABASE IF NOT EXISTS %s DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;" % uri.database
|
|
|
|
|
print(sql)
|
2022-04-24 14:35:13 +08:00
|
|
|
|
# 执行创建数据库的sql
|
|
|
|
|
cursor.execute(sql)
|
|
|
|
|
conn.commit()
|
|
|
|
|
|
|
|
|
|
|
2023-09-03 21:17:55 +08:00
|
|
|
|
init_db()
|