comment-server/lbry_comment_server/writes.py

42 lines
1.1 KiB
Python
Raw Normal View History

2019-05-21 05:00:01 -04:00
import aiojobs
import atexit
from asyncio import coroutine
import lbry_comment_server.database as db
2019-05-21 06:56:27 -04:00
import logging
logger = logging.getLogger(__name__)
2019-05-21 05:00:01 -04:00
# DatabaseWriter should be instantiated on startup
class DatabaseWriter(object):
_writer = None
def __init__(self, db_file):
if not DatabaseWriter._writer:
self.conn = db.obtain_connection(db_file)
DatabaseWriter._writer = self
atexit.register(self.cleanup)
2019-05-21 06:56:27 -04:00
logging.info('Database writer has been created at %s', repr(self))
2019-05-21 05:00:01 -04:00
else:
2019-05-21 06:56:27 -04:00
logging.warning('Someone attempted to insantiate DatabaseWriter')
2019-05-21 05:00:01 -04:00
raise TypeError('Database Writer already exists!')
def cleanup(self):
2019-05-21 06:56:27 -04:00
logging.info('Cleaning up database writer')
2019-05-21 05:00:01 -04:00
DatabaseWriter._writer = None
self.conn.close()
@property
def connection(self):
return self.conn
async def create_comment_scheduler():
return await aiojobs.create_scheduler(limit=1, pending_limit=0)
async def write_comment(**comment):
with DatabaseWriter._writer.connection as conn:
return await coroutine(db.create_comment)(conn, **comment)