openmedialibrary/oml/item/covers.py

78 lines
2.1 KiB
Python
Raw Normal View History

2014-05-04 17:26:43 +00:00
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
2014-05-16 08:06:11 +00:00
from __future__ import division
2014-05-04 17:26:43 +00:00
import sqlite3
import Image
from StringIO import StringIO
from settings import covers_db_path
class Covers(dict):
def __init__(self, db):
self._db = db
2014-05-17 09:24:17 +00:00
self.create()
2014-05-04 17:26:43 +00:00
def connect(self):
2014-05-17 09:24:17 +00:00
conn = sqlite3.connect(self._db, timeout=10)
return conn
2014-05-04 17:26:43 +00:00
def create(self):
2014-05-17 09:24:17 +00:00
conn = self.connect()
c = conn.cursor()
2014-05-04 17:26:43 +00:00
c.execute(u'CREATE TABLE IF NOT EXISTS cover (id varchar(64) unique, data blob)')
c.execute(u'CREATE TABLE IF NOT EXISTS setting (key varchar(256) unique, value text)')
if int(self.get_setting(c, 'version', 0)) < 1:
self.set_setting(c, 'version', 1)
def get_setting(self, c, key, default=None):
c.execute(u'SELECT value FROM setting WHERE key = ?', (key, ))
for row in c:
return row[0]
return default
def set_setting(self, c, key, value):
c.execute(u'INSERT OR REPLACE INTO setting values (?, ?)', (key, str(value)))
def black(self):
img = Image.new('RGB', (80, 128))
o = StringIO()
img.save(o, format='jpeg')
data = o.getvalue()
o.close()
return data
def __getitem__(self, id, default=None):
sql = u'SELECT data FROM cover WHERE id=?'
2014-05-17 09:24:17 +00:00
conn = self.connect()
c = conn.cursor()
2014-05-04 17:26:43 +00:00
c.execute(sql, (id, ))
data = default
for row in c:
data = row[0]
break
c.close()
2014-05-17 09:24:17 +00:00
conn.close()
2014-05-04 17:26:43 +00:00
return data
def __setitem__(self, id, data):
sql = u'INSERT OR REPLACE INTO cover values (?, ?)'
2014-05-17 09:24:17 +00:00
conn = self.connect()
c = conn.cursor()
2014-05-04 17:26:43 +00:00
data = sqlite3.Binary(data)
c.execute(sql, (id, data))
2014-05-17 09:24:17 +00:00
conn.commit()
2014-05-04 17:26:43 +00:00
c.close()
2014-05-17 09:24:17 +00:00
conn.close()
2014-05-04 17:26:43 +00:00
def __delitem__(self, id):
sql = u'DELETE FROM cover WHERE id = ?'
2014-05-17 09:24:17 +00:00
conn = self.connect()
c = conn.cursor()
2014-05-04 17:26:43 +00:00
c.execute(sql, (id, ))
2014-05-17 09:24:17 +00:00
conn.commit()
2014-05-04 17:26:43 +00:00
c.close()
2014-05-17 09:24:17 +00:00
conn.close()
2014-05-04 17:26:43 +00:00
covers = Covers(covers_db_path)