Add database module

This commit is contained in:
Joscha 2018-07-31 15:18:57 +00:00
parent 339d3ca516
commit bb2dadb862
3 changed files with 39 additions and 1 deletions

View file

@ -1,6 +1,7 @@
from .bot import * from .bot import *
from .cookiejar import * from .cookiejar import *
from .connection import * from .connection import *
from .database import *
from .exceptions import * from .exceptions import *
from .room import * from .room import *
from .utils import * from .utils import *
@ -9,6 +10,7 @@ __all__ = (
bot.__all__ + bot.__all__ +
connection.__all__ + connection.__all__ +
cookiejar.__all__ + cookiejar.__all__ +
database.__all__ +
exceptions.__all__ + exceptions.__all__ +
room.__all__ + room.__all__ +
utils.__all__ utils.__all__

31
yaboli/database.py Normal file
View file

@ -0,0 +1,31 @@
import asyncio
import sqlite3
from .utils import *
__all__ = ["Database", "operation"]
def operation(func):
async def wrapper(self, *args, **kwargs):
async with self as db:
return await asyncify(func, db, *args, **kwargs)
return wrapper
class Database:
def __init__(self, database):
self._connection = sqlite3.connect(database, check_same_thread=False)
self._lock = asyncio.Lock()
self.initialize(self._connection)
def initialize(self, db):
pass
async def __aenter__(self, *args, **kwargs):
await self._lock.__aenter__(*args, **kwargs)
return self._connection
async def __aexit__(self, *args, **kwargs):
return await self._lock.__aexit__(*args, **kwargs)

View file

@ -1,10 +1,11 @@
import asyncio import asyncio
import logging import logging
import time import time
import functools
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
__all__ = [ __all__ = [
"parallel", "parallel", "asyncify",
"mention", "mention_reduced", "similar", "mention", "mention_reduced", "similar",
"format_time", "format_time_delta", "format_time", "format_time_delta",
"Session", "Listing", "Message", "Session", "Listing", "Message",
@ -14,6 +15,10 @@ __all__ = [
# alias for parallel message sending # alias for parallel message sending
parallel = asyncio.ensure_future parallel = asyncio.ensure_future
async def asyncify(func, *args, **kwargs):
func_with_args = functools.partial(func, *args, **kwargs)
return await asyncio.get_event_loop().run_in_executor(None, func_with_args)
def mention(nick): def mention(nick):
return "".join(c for c in nick if c not in ".!?;&<'\"" and not c.isspace()) return "".join(c for c in nick if c not in ".!?;&<'\"" and not c.isspace())