python-feedgen/feedgen/util.py

49 lines
1.6 KiB
Python
Raw Permalink Normal View History

2013-04-26 14:59:44 +02:00
# -*- coding: utf-8 -*-
'''
2013-05-04 22:54:43 +02:00
feedgen.util
~~~~~~~~~~~~
2013-04-26 14:59:44 +02:00
This file contains helper functions for the feed generator module.
:copyright: 2013, Lars Kiesow <lkiesow@uos.de>
2013-05-03 17:13:08 +02:00
:license: FreeBSD and LGPL, see license.* for more details.
2013-04-26 14:59:44 +02:00
'''
def ensure_format(val, allowed, required, allowed_values=None, defaults=None):
2013-04-28 21:59:56 +02:00
'''Takes a dictionary or a list of dictionaries and check if all keys are in
the set of allowed keys, if all required keys are present and if the values
of a specific key are ok.
2013-12-01 19:42:55 +01:00
:param val: Dictionaries to check.
:param allowed: Set of allowed keys.
:param required: Set of required keys.
2013-04-28 21:59:56 +02:00
:param allowed_values: Dictionary with keys and sets of their allowed values.
2013-12-01 19:42:55 +01:00
:param defaults: Dictionary with default values.
:returns: List of checked dictionaries.
2013-04-28 21:59:56 +02:00
'''
2013-04-26 14:59:44 +02:00
if not val:
return None
if allowed_values is None:
allowed_values = {}
if defaults is None:
defaults = {}
2013-04-26 14:59:44 +02:00
# Make shure that we have a list of dicts. Even if there is only one.
if not isinstance(val, list):
val = [val]
for elem in val:
if not isinstance(elem, dict):
raise ValueError('Invalid data (value is no dictionary)')
# Set default values
for k,v in defaults.iteritems():
elem[k] = elem.get(k, v)
2013-04-26 14:59:44 +02:00
if not set(elem.keys()) <= allowed:
raise ValueError('Data contains invalid keys')
if not set(elem.keys()) >= required:
raise ValueError('Data contains not all required keys')
for k,v in allowed_values.iteritems():
if elem.get(k) and not elem[k] in v:
raise ValueError('Invalid value for %s' % k )
return val