Created
July 15, 2010 21:19
-
-
Save kennethreitz/477550 to your computer and use it in GitHub Desktop.
Store binaries smoothly within code (for pre-binded applications)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" 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