def _tag(value): if isinstance(value, CheckerSessionObject): return {" ch": dict((k, _tag(v)) for k, v in iteritems(value))} elif isinstance(value, MeansTest): return {" mt": dict((k, _tag(v)) for k, v in iteritems(value))} elif isinstance(value, tuple): return {" t": [_tag(x) for x in value]} elif isinstance(value, uuid.UUID): return {" u": value.hex} elif isinstance(value, bytes): return {" b": b64encode(value).decode("ascii")} elif callable(getattr(value, "__html__", None)): return {" m": text_type(value.__html__())} elif isinstance(value, list): return [_tag(x) for x in value] elif isinstance(value, datetime): return {" d": http_date(value)} elif isinstance(value, dict): return dict((k, _tag(v)) for k, v in iteritems(value)) elif isinstance(value, str): try: return text_type(value) except UnicodeError: raise UnexpectedUnicodeError( u"A byte string with " u"non-ASCII data was passed to the session system " u"which can only store unicode strings. Consider " u"base64 encoding your string (String was %r)" % value ) return value
def _tag(value): if isinstance(value, CheckerSessionObject): return {" ch": dict((k, _tag(v)) for k, v in iteritems(value))} elif isinstance(value, MeansTest): return {" mt": dict((k, _tag(v)) for k, v in iteritems(value))} elif isinstance(value, tuple): return {" t": [_tag(x) for x in value]} elif isinstance(value, uuid.UUID): return {" u": value.hex} elif isinstance(value, bytes): return {" b": b64encode(value).decode("ascii")} elif callable(getattr(value, "__html__", None)): return {" m": text_type(value.__html__())} elif isinstance(value, list): return [_tag(x) for x in value] elif isinstance(value, datetime): return {" d": http_date(value)} elif isinstance(value, dict): return dict((k, _tag(v)) for k, v in iteritems(value)) elif isinstance(value, str): try: return text_type(value) except UnicodeError: raise UnexpectedUnicodeError( u"A byte string with " u"non-ASCII data was passed to the session system " u"which can only store unicode strings. Consider " u"base64 encoding your string (String was %r)" % value) return value
def get_namespace(self, namespace, lowercase=True, trim_namespace=True): """Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage:: app.config['IMAGE_STORE_TYPE'] = 'fs' app.config['IMAGE_STORE_PATH'] = '/var/app/images' app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com' image_store_config = app.config.get_namespace('IMAGE_STORE_') The resulting dictionary `image_store` would look like:: { 'type': 'fs', 'path': '/var/app/images', 'base_url': 'http://img.website.com' } This is often useful when configuration options map directly to keyword arguments in functions or class constructors. :param namespace: a configuration namespace :param lowercase: a flag indicating if the keys of the resulting dictionary should be lowercase :param trim_namespace: a flag indicating if the keys of the resulting dictionary should not include the namespace .. versionadded:: 1.0 """ rv = {} for k, v in iteritems(self): if not k.startswith(namespace): continue if trim_namespace: key = k[len(namespace):] else: key = k if lowercase: key = key.lower() rv[key] = v return rv
def merge_branches(self, dictionary, sep='_'): '''Merge the branches where a key has only one value. This resolves the problem of getting a plain dictionary with any key containing the 'sep' element. Parameters ---------- dictionary: dict dictionary for which we want to merge branches sep: string, optional string used to merge the key and the value of the elements of a dictionary in different layers. Default is '_'. Returns ------- new_dict: dict a new dictionary with the branches merged ''' for k, v in iteritems(dictionary): if isinstance(v, dict): if len(dictionary.keys()) == 1: for vkey in v.keys(): dictionary[k + sep + vkey] = v[vkey] dictionary.pop(k) self.merge_branches(v) return dictionary
def get_namespace(self, namespace, lowercase=True, trim_namespace=True): """根据字符串返回和前缀相符合的Flask选项。 示例用法: >>> app.config['IMAGE_STORE_TYPE'] = 'fs' >>> app.config['IMAGE_STORE_PATH'] = '/var/app/images' >>> app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com' >>> image_store_config = app.config.get_namespace('IMAGE_STORE_') 结果字典`image_store`看上去像这样: { 'type': 'fs', 'path': '/var/app/images', 'base_url': 'http://img.website.com' } 当需要根据配置的参数,渲染为作为函数或类的传入参数时,这个方法 十分不错。 :param namespace: 配置的namespace :param lowercase: 选项是否转为小写的 :param trim_namespace: 是否去除选项中的空格 """ rv = {} for k, v in iteritems(self): if not k.startswith(namespace): continue if trim_namespace: key = k[len(namespace) :] else: key = k if lowercase: key = key.lower() rv[key] = v return rv
def list_templates(self): res = [] ctx = _request_ctx_stack.top for ident, theme in iteritems(ctx.app.theme_manager.themes): res.extend('_themes/%s/%s' % (ident, t) for t in theme.jinja_loader.list_templates()) return res
def _iter_app_blueprint_loaders(self): for name, blueprint in iteritems(self.app.blueprints): if name in self.app.feature_blueprint_names: continue loader = blueprint.jinja_loader if loader is not None: yield loader
def get_namespace(self, namespace, lowercase=True, trim_namespace=True): """获取命名空间""" rv = {} for k, v in iteritems(self): if not k.startswith(namespace): continue if trim_namespace: key = k[len(namespace):] else: key = k if lowercase: key = key.lower() rv[key] = v return rv
def _get_environment(self, env, config): """Return a dictionary containing the top level values updated with those from the environment. :param env: The name of the environment as a string :param config: the configuration mapping :return: a dictionary """ # Get the top level keys defaults = {k: v for k, v in iteritems(config) if k != 'environments'} try: defaults.update(config['environments'][env]) return defaults except KeyError as e: msg = 'Unable to find %s environment in configuration file' % env raise ConfigError(msg)
def find_best_app(module): """Given a module instance this tries to find the best possible application in the module or raises an exception. """ from . import Flask # Search for the most common names first. for attr_name in 'app', 'application': app = getattr(module, attr_name, None) if app is not None and isinstance(app, Flask): return app # Otherwise find the only object that is a Flask instance. matches = [v for k, v in iteritems(module.__dict__) if isinstance(v, Flask)] if len(matches) == 1: return matches[0] raise NoAppException('Failed to find application in module "%s". Are ' 'you sure it contains a Flask application? Maybe ' 'you wrapped it in a WSGI middleware or you are ' 'using a factory function.' % module.__name__)
def find_best_app(module): """Given a module instance this tries to find the best possible application in the module or raises an exception. """ from . import Flask # Search for the most common names first. for attr_name in 'app', 'application': app = getattr(module, attr_name, None) if app is not None and isinstance(app, Flask): return app # Otherwise find the only object that is a Flask instance. matches = [ v for k, v in iteritems(module.__dict__) if isinstance(v, Flask) ] if len(matches) == 1: return matches[0] raise NoAppException('Failed to find application in module "%s". Are ' 'you sure it contains a Flask application? Maybe ' 'you wrapped it in a WSGI middleware or you are ' 'using a factory function.' % module.__name__)
def object_hook(obj): if len(obj) != 1: return obj the_key, the_value = next(iteritems(obj)) if the_key == " t": return tuple(the_value) elif the_key == " u": return uuid.UUID(the_value) elif the_key == " b": return b64decode(the_value) elif the_key == " m": return Markup(the_value) elif the_key == " d": return parse_date(the_value) elif the_key == " ch": c = CheckerSessionObject() c.update(the_value) return c elif the_key == " mt": m = MeansTest() m.update(the_value) return m return obj
def remove_null_elements(self, dictionary): '''This methods removes the null elements of a plain dictionary Parameters ---------- dictionary: dict dictionary for which we want to remove the null elements Returns ------- new_dict: dict a new dictionary without the null elements ''' new_dict = OrderedDict() for k, v in iteritems(dictionary): if v != 0.: new_dict[k] = dictionary[k] return new_dict
def to_json(self, value): # JSON objects may only have string keys, so don't bother tagging the # key here. return dict((k, self.serializer.tag(v)) for k, v in iteritems(value))
def plot_nested_pie(self, dictionary, ax=None, radius=1., delta=0.2, dontlabel=None, breakdonut=True, metric='energy use', units='kW*h'): '''This method appends a pie plot from a nested dictionary to an axes of matplotlib object. If all the elements of the dictionary are float values it will make a simple pie plot with those values. If there are other nested dictionaries it will continue plotting them in a nested pie plot. Parameters ---------- dictionary: dict dictionary containing other dictionaries and/or float numbers for which the pie plot is going to be created. ax: matplotlib axes object, optional axes object where the plot is going to be appended. Default is None. radius: float, optional radius of the outer layer of the pie plot. Default is 1. delta: float, optional desired difference between the radius of two consecutive pie plot layers. Default is 0.2. dontlabel: list, optional list of items to not be labeled for more clarity. Default is None. breakdonut: boolean, optional if true it will not show the non labeled slices. Default is True. metric: string, optional indicates the metric that is being plotted. Notice that this is only used for the title of the plot. Default is 'energy use'. units: string, optional indicates the units used for the metric. Notice that this is only used for the title of the plot. Default is 'kW*h'. ''' # Initialize the pie plot if not initialized yet if ax is None: _, ax = plt.subplots() if dontlabel is None: dontlabel = [] # Get the color map to be used in this pie cmap = plt.get_cmap('rainbow') labels = [] # Parse the color indexes to be used in this pie color_indexes = self.parse_color_indexes(dictionary) # Initialize the color indexes to be used in this layer cindexes_layer = [0] # Initialize the list of values to plot in this layer vals = [] # Initialize a new dictionary for the next inner layer new_dict = OrderedDict() # Initialize the shifts for the required indices shift = np.zeros(len(dictionary.keys())) # Initialize a counter for the loop i = 0 # Go through every component in this layer for k_outer, v_outer in iteritems(dictionary): # Calculate the slice size of this component vals.append(self.sum_dict(v_outer)) # Append the new label if not end point (if not in dontlabel) last_key = k_outer.split('__')[-1] label = last_key if not any(k_outer.startswith(dntlbl) \ for dntlbl in dontlabel) else '' labels.append(label) # Check if this component has nested dictionaries if isinstance(v_outer, dict): # If it has, add them to the new dictionary for k_inner, v_inner in iteritems(v_outer): # Give a unique nested key name to it new_dict[k_outer + '__' + k_inner] = v_inner # Check if this component is already a float end point elif isinstance(v_outer, float): # If it is, add it to the new dictionary new_dict[k_outer] = v_outer # Count the number of elements in this component n = self.count_elements(v_outer) # Append the index of this component according to its # number of components in order to follow a progressive # chromatic circle cindexes_layer.append(cindexes_layer[-1] + n) # Make a shift if this is not an end point to do not use # the same color as the underlying end points. Make this # shift something characteristic of this layer by making # use of its radius shift[i] = 0 if n == 1 else 60 * radius # Do not label this slice in the next layer if this was # already an end point or a null slice if n == 1: dontlabel.append(k_outer) # Increase counter i += 1 # Assign the colors to every component in this layer colors = cmap((color_indexes[[cindexes_layer[:-1]]] + \ shift).astype(int)) # If breakdonut=True show a blank in the unlabeled items if breakdonut: for j, l in enumerate(labels): if l is '': colors[j] = [0., 0., 0., 0.] # Append the obtained slice values of this layer to the axes ax.pie(np.array(vals), radius=radius, labels=labels, labeldistance=radius, colors=colors, wedgeprops=dict(width=0.2, edgecolor='w', linewidth=0.3)) # Keep nesting if there is still any dictionary between the values if not all(isinstance(v, float) for v in dictionary.values()): self.plot_nested_pie(new_dict, ax, radius=radius - delta, dontlabel=dontlabel, metric=metric, units=units) # Don't continue nesting if all components were float end points else: plt.title('Total {metric} = {value:.2f} {units}'.format(\ metric=metric, value=self.sum_dict(dictionary), units=units)) # Equal aspect ratio ensures that pie is drawn as a circle ax.axis('equal') plt.show()
def serialize_dict(self, value): return dict((k, self.checkTag(v)) for k, v in iteritems(value))
def serialize_means_test(self, value): return { " mt": dict((k, self.checkTag(v)) for k, v in iteritems(value)) }
def serialize_checker_session_object(self, value): return { " ch": dict((k, self.checkTag(v)) for k, v in iteritems(value)) }
def load_config(self): config = dict([(key, value) for key, value in iteritems(self.options) if key in self.cfg.settings and value is not None]) for key, value in iteritems(config): self.cfg.set(key.lower(), value)