retry connection to database after fail

This commit is contained in:
kiriharu 2021-01-30 14:56:24 +03:00
parent 6475271234
commit c117a8246c
2 changed files with 15 additions and 6 deletions

View File

@ -2,7 +2,9 @@ from aiogram import Bot, Dispatcher, executor
from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.contrib.fsm_storage.memory import MemoryStorage
from tgbot.middlewares import UserMiddleware, WriteCommandMetric, LoggingMiddleware, ThrottlingMiddleware from tgbot.middlewares import UserMiddleware, WriteCommandMetric, LoggingMiddleware, ThrottlingMiddleware
from tortoise import Tortoise from tortoise import Tortoise
from tortoise.exceptions import DBConnectionError
from loguru import logger from loguru import logger
from asyncio import sleep
import config import config
import handlers import handlers
@ -17,12 +19,17 @@ async def database_init():
f"{config.MYSQL_HOST}:{config.MYSQL_PORT}/{config.MYSQL_DATABASE}" f"{config.MYSQL_HOST}:{config.MYSQL_PORT}/{config.MYSQL_DATABASE}"
else: else:
db_url = "sqlite://db.sqlite3" db_url = "sqlite://db.sqlite3"
await Tortoise.init( try:
db_url=db_url, await Tortoise.init(
modules={ db_url=db_url,
'models': ['tgbot.models'] modules={
} 'models': ['tgbot.models']
) }
)
except DBConnectionError:
logger.error("Connection to database failed.")
await sleep(10)
await database_init()
await Tortoise.generate_schemas() await Tortoise.generate_schemas()
logger.info("Tortoise inited!") logger.info("Tortoise inited!")

View File

@ -10,6 +10,8 @@ def userdata_required(func):
setattr(func, 'userdata_required', True) setattr(func, 'userdata_required', True)
return func return func
# I think, now it useless
class UserMiddleware(BaseMiddleware): class UserMiddleware(BaseMiddleware):