Skip to content

Instantly share code, notes, and snippets.

@davbo davbo/preloader.py
Created May 29, 2013

Embed
What would you like to do?
Preloads JSON & images for our University Museums offline JavaScript applicaiton
import json
import urllib2
import os
import codecs
from urlparse import urlparse
from string import Template
build_dir = os.environ['TARGET_FOLDER']
MUSEUMS_ENDPOINT = "SNIP!"
PRELOAD_IMAGE_PATH = "%s/images/preloaded" % build_dir
INDEX_PATH = "%s/index.html" % build_dir
HAL_EMBED = '_embedded'
def get_json():
return json.load(urllib2.urlopen(MUSEUMS_ENDPOINT))
def preload_url(url):
parsed = urlparse(url)
download_path = os.path.join(PRELOAD_IMAGE_PATH, parsed.path[1:])
try:
os.makedirs(download_path.rpartition('/')[0])
except OSError:
pass # Just means the path already exists
with open(download_path, 'w') as fp:
fp.write(urllib2.urlopen(url).read())
path = download_path.partition('/')[2]
print "Image preloaded: %s -> %s" % (url, path)
return path
def preload(response):
"""Reads our JSON response and mirrors the images of Floorplans and Museum
items into the phonegap build folder. Returns a dictionary of all the files
original locations and their mirrored location within the phonegap build.
"""
try:
os.makedirs(PRELOAD_IMAGE_PATH)
except OSError:
pass
preloaded = {}
for museum in response[HAL_EMBED]:
preloaded[museum[HAL_EMBED]['floorplan']['image']] = preload_url(museum[HAL_EMBED]['floorplan']['image'])
preloaded[museum['front_page_image_url']] = preload_url(museum['front_page_image_url'])
for item in museum[HAL_EMBED]['items']:
preloaded[item['cropped_image_resize']] = preload_url(item['cropped_image_resize'])
return preloaded
def write_json(bootstrap, preloaded):
"""Uses a simple Python string template to write a "bootstrappped" JSON
response into the index.html for our phonegap build. This way we always
ship with the most up-to-date JSON.
Also writes the JSON for which images have been preloaded. Handled in JS
by app/preloaded.js
"""
with codecs.open(INDEX_PATH, 'r+', 'utf-8') as indexfp:
index = Template(indexfp.read())
indexfp.seek(0)
jsons = json.dumps(bootstrap)
preloaded = json.dumps(preloaded)
indexfp.write(index.substitute(museums=jsons, preload=preloaded))
print "Embedded JSON"
if __name__ == '__main__':
bootstrap = get_json()
preloaded_files = preload(bootstrap)
write_json(bootstrap, preloaded_files)
print "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.