Serving static content from egg files with Twisted

So it’s been a long time since I started working on AIRi package and now it’s time to start addressing performance issues. One of the problems was that I noticed it wasn’t using the browser cache at all!

By researching I noticed the problem was actually my PkgFile class which was dumping content from the egg file using pkg_resources.resource_stream…. Which in fact isn’t the most efficient way, as pkg_resources actually uncompress the hole egg file (or just uses a folder if accessible).

So the way to serve static content from either egg files or folder with pkg_resources in Twisted is REALLY simple, here’s an example:

from twisted.web.resource import Resource
from twisted.web.static import File
from twisted.web.server import Site
from twisted.internet import reactor
import pkg_resources

root = Resource()
PATH=pkg_resources.resource_filename("airi", "/media")
root.putChild("media", File(PATH), defaultType=None)
reactor.listenTCP(8000, Site(root))
reactor.run()

This is actually the most important line:

PATH=pkg_resources.resource_filename("airi", "/media")

Here airi is the name of the package we want to resolve, and media is a path inside that package, airi package will be resolved to either an egg file or a real folder by setup tools.

Advertisements
This entry was posted in egg files, python, setup tools, twisted. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s