Created
May 23, 2010 21:56
-
-
Save shazow/411284 to your computer and use it in GitHub Desktop.
More concise handling of request parameters.
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
def get_many(d, required=[], optional=[], one_of=[]): | |
""" | |
Returns a predictable number of elements out of `d` in a list for auto-expanding. | |
Keys in `required` will raise KeyError if not found in `d`. | |
Keys in `optional` will return None if not found in `d`. | |
Keys in `one_of` will raise KeyError if none exist, otherwise return the first in `d`. | |
Example usage: | |
uid, action, limit, offset = get_many(request.params, required=['uid', 'action'], optional=['limit', 'offset']) | |
""" | |
d = d or {} | |
r = [d[k] for k in required] | |
r += [d.get(k)for k in optional] | |
if one_of: | |
for k in (k for k in one_of if k in d): | |
return r + [d[k]] | |
raise KeyError("Missing a one_of value.") | |
return r |
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
# Unit tests for get_many | |
def test_get_many(self): | |
params = dict((n,n) for n in range(5)) # Dict with keys and values of 0, 1, 2, 3, 4 | |
self.assertEqual(get_many(params), []) | |
self.assertEqual(get_many(params, required=[1, 2]), [1, 2]) | |
self.assertEqual(get_many(params, optional=[1, 2]), [1, 2]) | |
self.assertEqual(get_many(params, optional=[6, 7, 8]), [None, None, None]) | |
self.assertEqual(get_many(params, one_of=[1, 2]), [1]) | |
self.assertEqual(get_many(params, one_of=[6, 1]), [1]) | |
self.assertEqual(get_many(params, optional=[6, 1]), [None, 1]) | |
self.assertEqual(get_many(params, required=[1, 2], optional=[6, 1]), [1, 2, None, 1]) | |
self.assertEqual(get_many(params, required=[1, 2], optional=[6, 1], one_of=[7, 8, 3]), [1, 2, None, 1, 3]) | |
self.assertRaises(KeyError, get_many, params, required=[1, 6]) | |
self.assertRaises(KeyError, get_many, params, one_of=[7, 6]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment