89 lines
2.8 KiB
Python
89 lines
2.8 KiB
Python
# -*- coding: utf-8 -*-
|
|
"default plugin for cache: set it in a simple dictionary"
|
|
# Copyright (C) 2013 Team tiramisu (see AUTHORS for all contributors)
|
|
#
|
|
# This program is free software; you can redistribute it and/or modify
|
|
# it under the terms of the GNU General Public License as published by
|
|
# the Free Software Foundation; either version 2 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU General Public License
|
|
# along with this program; if not, write to the Free Software
|
|
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
|
#
|
|
# ____________________________________________________________
|
|
|
|
from os import unlink
|
|
from os.path import basename, splitext, join
|
|
import sqlite3
|
|
from glob import glob
|
|
from ..util import SerializeObject
|
|
|
|
|
|
class Setting(SerializeObject):
|
|
""":param extension: database file extension (by default: db)
|
|
:param dir_database: root database directory (by default: /tmp)
|
|
"""
|
|
extension = 'db'
|
|
dir_database = '/tmp'
|
|
|
|
|
|
setting = Setting()
|
|
|
|
|
|
def _gen_filename(name):
|
|
return join(setting.dir_database, '{0}.{1}'.format(name,
|
|
setting.extension))
|
|
|
|
|
|
def list_sessions():
|
|
names = []
|
|
for filename in glob(_gen_filename('*')):
|
|
names.append(basename(splitext(filename)[0]))
|
|
return names
|
|
|
|
|
|
def delete_session(session_id):
|
|
unlink(_gen_filename(session_id))
|
|
|
|
|
|
class Storage(object):
|
|
__slots__ = ('_conn', '_cursor', 'persistent', 'session_id', 'serializable')
|
|
storage = 'sqlite3'
|
|
|
|
def __init__(self, session_id, persistent, test=False):
|
|
self.persistent = persistent
|
|
if self.persistent:
|
|
self.serializable = True
|
|
else:
|
|
self.serializable = False
|
|
self.session_id = session_id
|
|
self._conn = sqlite3.connect(_gen_filename(self.session_id))
|
|
self._conn.text_factory = str
|
|
self._cursor = self._conn.cursor()
|
|
|
|
def execute(self, sql, params=None, commit=True):
|
|
if params is None:
|
|
params = tuple()
|
|
self._cursor.execute(sql, params)
|
|
if commit:
|
|
self._conn.commit()
|
|
|
|
def select(self, sql, params=None, only_one=True):
|
|
self.execute(sql, params=params, commit=False)
|
|
if only_one:
|
|
return self._cursor.fetchone()
|
|
else:
|
|
return self._cursor.fetchall()
|
|
|
|
def __del__(self):
|
|
self._cursor.close()
|
|
self._conn.close()
|
|
if not self.persistent:
|
|
delete_session(self.session_id)
|