Plugin developers often want to supply data files (web templates,
images, etc) with their package, let's see how to do this using
setuptools resource management system.
If there are still some lazy people reading this, get an updated
version of the code. So, on your plugin's setup.py, add a
package_data argument to setup():
Create a data directory in foo's plugin directory, and create some files:
$ mkdir plugins/foo/data
$ echo "Hello this is foo\n" > plugins/foo/data/foobar.tmpl
Don't forget to re-run pythonsetup.pydevelop in the foo plugin
directory. The next step is to fetch those data files via our plugin_loader:
for entrypoint in pkg_resources.iter_entry_points("my.plugins"):
plugin_class = entrypoint.load()
print 'Plugin %s: %s' % (repr(entrypoint.name), repr(plugin_class))
requirement = pkg_resources.Requirement.parse(plugin_class.__name__)
tmpl = 'data/foobar.tmpl'
data_contents = pkg_resources.resource_listdir(requirement, 'data')
print 'data contents : %s' % repr(data_contents)
# let's find and read a data file in our plugin
if pkg_resources.resource_exists(requirement, tmpl):
foo_bar = pkg_resources.resource_string(requirement, tmpl)
# contents of foobar.tmpl as a string
print 'tmpl contents : %s' % repr(foo_bar)
else:
print '%s not found :-(' % repr(tmpl)
Given the plugin's name, we tell pkg_resources to find the plugin's
resources given their relative location from the plugin point of
view. That's fun, no ? You don't need to care about a global variable
storing the full path of the data files, or whatever crappy monkey-code !
I promise, next time i'll start playing with plugin API management,
probably with interfaces :-)