View Single Post
Old 03-28-2016, 08:28 AM   #736
JJanssen
Member
JJanssen began at the beginning.
 
Posts: 16
Karma: 24
Join Date: Jun 2009
Device: Kindle Paperwhite 1
Quote:
Originally Posted by eschwartz View Post
Sure.
It's a trick I saw used elsewhere, which makes for much more reusable code (and which I should've used back when someone was having a lot of trouble editing an attached python script ).
I've changed the bits around a little. It now uses the current library as the default, but you can also pass it an explicit path if you want to.
Code:
def init_cache(library_path = None):
	from calibre.db.backend import DB
	from calibre.db.cache import Cache
	from calibre.utils.config import prefs
	if library_path == None:
		library_path = prefs['library_path']
	backend = DB(library_path)
	cache = Cache(backend)
	cache.init()
	return cache

cache = init_cache()
#cache = init_cache('/Users/jasper/Documents/Calibre Main Library/')
#cache = init_cache(library_path = '/Users/jasper/Documents/Calibre Test Library/')
#
# The parameter can be empty, for the currently opened library, 
# or you can pass a specific Library's path if you wish.
#
#-------------------- Usage specific code starts here ------------------

import math
from collections import defaultdict

series_info = defaultdict(dict)
fract_ids = []
[.... etc ....]
Putting the prefs import inside the init_cache function is just more elegant, to my mind, and it also makes the thing even more reusable/readable. Putting the imports for math and defaultdict after the initialisation of the cache object is not *strictly* Python best practice, but in this case I think it's warranted because those are imports for the specific code we're writing in this go-around, and when ordered like this, everything up to line 19 is a straight copy/paste over to any script that wants to work with a calibre DB.

Last edited by JJanssen; 03-28-2016 at 08:31 AM.
JJanssen is offline   Reply With Quote