Created
May 21, 2014 19:56
-
-
Save Slater-Victoroff/cf4910470d42b4fb6e39 to your computer and use it in GitHub Desktop.
Automatic Key Finding
This file contains hidden or 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
class MissingKeyException(Exception): | |
""" | |
If we can't figure out what the key is of an item being saved, we just say so. | |
Should probably make a better error message that says what we can figure out and what they can do about it. | |
""" | |
def __init__(self, data_structure): | |
self.ds = data_structure | |
def __str__(self): | |
return "Could not determine key for: %s" % self.ds.__repr__() | |
def find_key(data_atom): | |
""" | |
Tries to find an appropriate S3 key from an arbitrary data structure | |
""" | |
if isinstance(data_atom, dict): | |
if len(data_atom.keys()) == 1: | |
current_key = data_atom.keys()[0] | |
else: | |
current_key = data_atom.get('key', False) or data_atom.get('title', False) or data_atom.get('name', False) | |
elif isinstance(data_atom, list) or isinstance(data_atom, tuple): | |
current_key = data_atom[0] | |
else: | |
raise MissingKeyException | |
return current_key |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment