Some plugins need to store data between Pyblosxom requests. Take for example my viewcounts plugin which keeps track of how many times a given entry has been viewed. This data is stored as a pickled dict of entryid -> view count in a viewcounts.dat file in my datadir.
My viewcounts plugin does two things. First, it displays the current number of times a given entry has been viewed. Second, it updates this number. This creates a class read/write serialization problem where two or more processes could be trying to read and modify the data at the same time. This is solved by serializing the processes so that only one process is reading and modifying the data at a time.
There are a couple of ways you can store this data. First, you could store it in a database--which handles serialization and all that sort of stuff for you in transactions.
The other way is to use the tools module's lock/unlock functions (from the Python Cookbook portalocker code). For example:
from Pyblosxom import tools
import pickle
def cb_start(args):
request = args["request"]
data = request.getData()
config = request.getConfiguration()
datadir = config["datadir"]
f = file(datadir + "/mydatafile.dat", "r+")
tools.lock(f, tools.LOCK_EX)
data["myplugin_datafile"] = f
data["myplugin_data"] = pickle.load(f)
def cb_story(args):
# We can use the data file anywhere--I'll just use it
# here to show the example code.
request = args["request"]
data = request.getData()
# get the data we saved in cb_start....
d = data["myplugin_data"]
# do our data modification here...
...
def cb_end(args):
request = args["request"]
data = request.getData()
f = data[""myplugin_datafile"]
d = data["myplugin_data"]
# set the pointer back to the beginning of the file
f.seek(0, 0)
# dump the modified data back to the file
pickle.dump(d, f, 1)
# close the file
f.close()
tools.unlock(f)
That's pretty much it.
changelog
Please keep comments appropriate. I reserve the right to remove anonymous comments, flames, spammy, inappropriate, and other comments that I deem to be worth removing.
Note: New comments get placed in a "draft" status and will NOT show up on the site until I explicitly approve it. Usually that happens within 24 hours, but sometimes I go away and it takes a day or two.
Note 2: There is now a preview button for those of you who want to see a preview! However, it doesn't quite work the way you'd think it should work. I'll look into adjusting it some day.
Note 3: If you can't for some reason post a comment, send me an email: willg at bluesock dot org.
All contents Copyright 1996 to 2008 Will Guaraldi.
This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.