Python marshmallow.fields.Dict() Examples
The following are 19
code examples of marshmallow.fields.Dict().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
marshmallow.fields
, or try the search function
.
Example #1
Source File: schema.py From packit with MIT License | 7 votes |
def specfile_path_pre(self, data: Dict, **kwargs): """ Method for pre-processing specfile_path value. Set it to downstream_package_name if specified, else leave unset. :param data: conf dictionary to process :return: processed dictionary """ if not data: # data is None when .packit.yaml is empty return data specfile_path = data.get("specfile_path", None) if not specfile_path: downstream_package_name = data.get("downstream_package_name", None) if downstream_package_name: data["specfile_path"] = f"{downstream_package_name}.spec" logger.debug( f'Setting `specfile_path` to "./{downstream_package_name}.spec".' ) else: # guess it? logger.debug( "Neither `specfile_path` nor `downstream_package_name` set." ) return data
Example #2
Source File: test_field_for_schema.py From marshmallow_dataclass with MIT License | 6 votes |
def test_override_container_type_with_type_mapping(self): type_mapping = [ (List, fields.List, List[int]), (Dict, fields.Dict, Dict[str, int]), (Tuple, fields.Tuple, Tuple[int, str, bytes]), ] for base_type, marshmallow_field, schema in type_mapping: class MyType(marshmallow_field): ... self.assertIsInstance(field_for_schema(schema), marshmallow_field) class BaseSchema(Schema): TYPE_MAPPING = {base_type: MyType} self.assertIsInstance( field_for_schema(schema, base_schema=BaseSchema), MyType )
Example #3
Source File: schemas.py From polyaxon with Apache License 2.0 | 6 votes |
def read( cls, kind: str, name: str, data: Union[str, Dict], parse_dates: bool = True ) -> "V1Events": import pandas as pd if isinstance(data, str): csv = cls.validate_csv(data) if parse_dates: df = pd.read_csv(csv, sep=V1Event.SEPARATOR, parse_dates=["timestamp"],) else: df = pd.read_csv(csv, sep=V1Event.SEPARATOR,) elif isinstance(data, dict): df = pd.DataFrame.from_dict(data) else: raise ValueError( "V1Events received an unsupported value type: {}".format(type(data)) ) return cls(name=name, kind=kind, df=df)
Example #4
Source File: schemas.py From polyaxon with Apache License 2.0 | 6 votes |
def get_summary(self) -> Dict: summary = {} step_summary = self._get_step_summary() if step_summary: summary["step"] = step_summary ts_summary = self._get_ts_summary() if step_summary: summary["timestamp"] = ts_summary if self.kind == V1ArtifactKind.METRIC: summary[self.kind] = { k: sanitize_np_types(v) for k, v in self.df.metric.describe().to_dict().items() } summary[self.kind]["last"] = sanitize_np_types(self.df.metric.iloc[-1]) return summary
Example #5
Source File: archiver.py From anchore-engine with Apache License 2.0 | 5 votes |
def __init__(self, task_id, account: str, image_tag_lookup_callback_fn: callable): """ :param account: :param image_tag_lookup_callback_fn: Function to get the full set of tags for an account, imageDigest tuple. Called as image_tag_lookup_fn(account, digest). Returns a list of CatalogImageDocker or ArchivedImageDocker objects """ self.task_id = task_id self.account = account self.tag_lookup_fn = image_tag_lookup_callback_fn self.image_tags_subset_matched = {} # Map image digests to the list of matched tags self.image_tags_full_match = {} # Map the image digests to their full tag sets, tracking that they are complete. self.image_tags = {} # Dict mapping image records to their full tag sets, where the image is partially matched
Example #6
Source File: schema.py From packit with MIT License | 5 votes |
def _deserialize( self, value: Any, attr: Optional[str], data: Optional[Mapping[ActionName, Any]], **kwargs, ) -> Dict: if not isinstance(value, dict): raise ValidationError(f"'dict' required, got {type(value)!r}.") self.validate_all_actions(actions=list(value)) data = {ActionName(key): val for key, val in value.items()} return data
Example #7
Source File: schemas.py From incubator-superset with Apache License 2.0 | 5 votes |
def make_query_context(self, data: Dict[str, Any]) -> QueryContext: query_context = QueryContext(**data) return query_context # pylint: enable=no-self-use
Example #8
Source File: schemas.py From incubator-superset with Apache License 2.0 | 5 votes |
def pre_load(self, data: Dict[str, Any]) -> None: # pylint: disable=no-self-use if data.get("slug"): data["slug"] = data["slug"].strip() data["slug"] = data["slug"].replace(" ", "-") data["slug"] = re.sub(r"[^\w\-]+", "", data["slug"])
Example #9
Source File: test_field_for_schema.py From marshmallow_dataclass with MIT License | 5 votes |
def test_builtin_dict(self): self.assertFieldsEqual( field_for_schema(dict), fields.Dict( keys=fields.Raw(required=True, allow_none=True), values=fields.Raw(required=True, allow_none=True), required=True, ), )
Example #10
Source File: test_field_for_schema.py From marshmallow_dataclass with MIT License | 5 votes |
def test_dict_from_typing(self): self.assertFieldsEqual( field_for_schema(Dict[str, float]), fields.Dict( keys=fields.String(required=True), values=fields.Float(required=True), required=True, ), )
Example #11
Source File: schemas.py From polyaxon with Apache License 2.0 | 5 votes |
def _get_ts_summary(self) -> Optional[Dict]: _count = self.df.timestamp.count() if _count == 0: return None return { "min": self.df.timestamp.iloc[0].isoformat(), "max": self.df.timestamp.iloc[-1].isoformat(), }
Example #12
Source File: schemas.py From polyaxon with Apache License 2.0 | 5 votes |
def _get_step_summary(self) -> Optional[Dict]: _count = self.df.step.count() if _count == 0: return None return { "count": sanitize_np_types(_count), "min": sanitize_np_types(self.df.step.iloc[0]), "max": sanitize_np_types(self.df.step.iloc[-1]), }
Example #13
Source File: schemas.py From polyaxon with Apache License 2.0 | 5 votes |
def to_dict(self, orient: str = "list") -> Dict: import numpy as np return self.df.replace({np.nan: None}).to_dict(orient=orient)
Example #14
Source File: test_converter.py From marshmallow-annotations with MIT License | 5 votes |
def test_can_convert_Dict_type_to_DictField(registry_): class HasDictField: mapping: typing.Dict[int, str] converter = BaseConverter(registry=registry_) generated_fields = converter.convert_all(HasDictField) assert isinstance(generated_fields["mapping"], fields.Dict)
Example #15
Source File: registry.py From marshmallow-annotations with MIT License | 5 votes |
def __init__(self, registry: Dict[type, FieldFactory] = None) -> None: if registry is None: registry = {} self._registry = {**self._registry, **registry}
Example #16
Source File: meaningful_locations.py From FlowKit with Mozilla Public License 2.0 | 4 votes |
def __init__( self, *, start_date_a: str, end_date_a: str, start_date_b: str, end_date_b: str, aggregation_unit: AnySpatialUnit, label: str, labels: Dict[str, Dict[str, dict]], tower_day_of_week_scores: Dict[str, float], tower_hour_of_day_scores: List[float], tower_cluster_radius: float = 1.0, tower_cluster_call_threshold: int = 0, event_types: Optional[Union[str, List[str]]], subscriber_subset: Union[dict, None] = None, ): # Note: all input parameters need to be defined as attributes on `self` # so that marshmallow can serialise the object correctly. self.start_date_a = start_date_a self.start_date_b = start_date_b self.end_date_a = end_date_a self.end_date_b = end_date_b self.aggregation_unit = aggregation_unit self.event_types = event_types self.label = label self.labels = labels self.tower_day_of_week_scores = tower_day_of_week_scores self.tower_hour_of_day_scores = tower_hour_of_day_scores self.tower_cluster_radius = tower_cluster_radius self.tower_cluster_call_threshold = tower_cluster_call_threshold self.subscriber_subset = subscriber_subset common_params = dict( labels=labels, label=label, event_types=event_types, subscriber_subset=subscriber_subset, tower_cluster_call_threshold=tower_cluster_call_threshold, tower_cluster_radius=tower_cluster_radius, tower_day_of_week_scores=tower_day_of_week_scores, tower_hour_of_day_scores=tower_hour_of_day_scores, ) locs_a = _make_meaningful_locations_object( start_date=start_date_a, end_date=end_date_a, **common_params ) locs_b = _make_meaningful_locations_object( start_date=start_date_b, end_date=end_date_b, **common_params ) self.q_meaningful_locations_od = MeaningfulLocationsOD( meaningful_locations_a=locs_a, meaningful_locations_b=locs_b, spatial_unit=aggregation_unit, )
Example #17
Source File: meaningful_locations.py From FlowKit with Mozilla Public License 2.0 | 4 votes |
def __init__( self, *, start_date: str, end_date: str, aggregation_unit: AnySpatialUnit, label_a: str, label_b: str, labels: Dict[str, Dict[str, dict]], tower_day_of_week_scores: Dict[str, float], tower_hour_of_day_scores: List[float], tower_cluster_radius: float = 1.0, tower_cluster_call_threshold: int = 0, event_types: Optional[Union[str, List[str]]], subscriber_subset: Union[dict, None] = None, ): # Note: all input parameters need to be defined as attributes on `self` # so that marshmallow can serialise the object correctly. self.start_date = start_date self.end_date = end_date self.aggregation_unit = aggregation_unit self.event_types = event_types self.label_a = label_a self.label_b = label_b self.labels = labels self.tower_day_of_week_scores = tower_day_of_week_scores self.tower_hour_of_day_scores = tower_hour_of_day_scores self.tower_cluster_radius = tower_cluster_radius self.tower_cluster_call_threshold = tower_cluster_call_threshold self.subscriber_subset = subscriber_subset common_params = dict( labels=labels, start_date=start_date, end_date=end_date, event_types=event_types, subscriber_subset=subscriber_subset, tower_cluster_call_threshold=tower_cluster_call_threshold, tower_cluster_radius=tower_cluster_radius, tower_day_of_week_scores=tower_day_of_week_scores, tower_hour_of_day_scores=tower_hour_of_day_scores, ) locs_a = _make_meaningful_locations_object(label=label_a, **common_params) locs_b = _make_meaningful_locations_object(label=label_b, **common_params) self.q_meaningful_locations_od = RedactedMeaningfulLocationsOD( meaningful_locations_od=MeaningfulLocationsOD( meaningful_locations_a=locs_a, meaningful_locations_b=locs_b, spatial_unit=aggregation_unit, ) )
Example #18
Source File: meaningful_locations.py From FlowKit with Mozilla Public License 2.0 | 4 votes |
def __init__( self, *, start_date: str, end_date: str, aggregation_unit: AnySpatialUnit, label: str, labels: Dict[str, Dict[str, dict]], tower_day_of_week_scores: Dict[str, float], tower_hour_of_day_scores: List[float], tower_cluster_radius: float = 1.0, tower_cluster_call_threshold: int = 0, event_types: Optional[Union[str, List[str]]], subscriber_subset: Union[dict, None] = None, ): # Note: all input parameters need to be defined as attributes on `self` # so that marshmallow can serialise the object correctly. self.start_date = start_date self.end_date = end_date self.aggregation_unit = aggregation_unit self.event_types = event_types self.label = label self.labels = labels self.tower_day_of_week_scores = tower_day_of_week_scores self.tower_hour_of_day_scores = tower_hour_of_day_scores self.tower_cluster_radius = tower_cluster_radius self.tower_cluster_call_threshold = tower_cluster_call_threshold self.subscriber_subset = subscriber_subset q_meaningful_locations = _make_meaningful_locations_object( label=label, labels=labels, start_date=start_date, end_date=end_date, event_types=event_types, subscriber_subset=subscriber_subset, tower_cluster_call_threshold=tower_cluster_call_threshold, tower_cluster_radius=tower_cluster_radius, tower_day_of_week_scores=tower_day_of_week_scores, tower_hour_of_day_scores=tower_hour_of_day_scores, ) self.q_meaningful_locations_aggregate = RedactedMeaningfulLocationsAggregate( meaningful_locations_aggregate=MeaningfulLocationsAggregate( meaningful_locations=q_meaningful_locations, spatial_unit=aggregation_unit, ) )
Example #19
Source File: response.py From aiohttp-apispec with MIT License | 4 votes |
def response_schema(schema, code=200, required=False, description=None): """ Add response info into the swagger spec Usage: .. code-block:: python from aiohttp import web from marshmallow import Schema, fields class ResponseSchema(Schema): msg = fields.Str() data = fields.Dict() @response_schema(ResponseSchema(), 200) async def index(request): return web.json_response({'msg': 'done', 'data': {}}) :param str description: response description :param bool required: :param schema: :class:`Schema <marshmallow.Schema>` class or instance :param int code: HTTP response code """ if callable(schema): schema = schema() def wrapper(func): if not hasattr(func, "__apispec__"): func.__apispec__ = {"schemas": [], "responses": {}, "parameters": []} func.__schemas__ = [] func.__apispec__["responses"]["%s" % code] = { "schema": schema, "required": required, "description": description, } return func return wrapper # For backward compatibility