Skip to content

Instantly share code, notes, and snippets.

@kennethreitz
Created July 15, 2010 21:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kennethreitz/477550 to your computer and use it in GitHub Desktop.
Save kennethreitz/477550 to your computer and use it in GitHub Desktop.
Store binaries smoothly within code (for pre-binded applications)
""" media.py -- Stores any files in python code for binding
By Kenneth Reitz - MIT License
Example Usage:
# initialize mediapool
media.init()
#save a file to mediapool
media.save('test_file')
#load a file from mediapool
media.get('test_file')
"""
import base64
import cStringIO
import io
import sys
import os
# Resource pool location
RESOURCES = '_media.py'
def init(path=RESOURCES):
"""Initializes media resource file"""
f = open(path, 'w')
f.write('_media = {}\n')
def save(path):
"""Store a file in the media resource pool"""
file_contents = base64.encodestring(open(path).read())
with open(RESOURCES, 'a') as f:
f.write('_media["%s"] = """%s"""\n' % (path, file_contents))
return True
def get(file_path):
"""Fetch a file from media resource pool, fallback on files"""
try:
import _media
file_contents = base64.decodestring(_media._media[file_path])
f = cStringIO.StringIO(file_contents)
except Exception, e:
print e
f = open(file_path)
return f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment