Skip to content

Instantly share code, notes, and snippets.

@davbo davbo/
Created May 29, 2013

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']
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:])
except OSError:
pass # Just means the path already exists
with open(download_path, 'w') as fp:
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.
except OSError:
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, 'r+', 'utf-8') as indexfp:
index = Template(
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.