本文整理汇总了Python中cattr.structure方法的典型用法代码示例。如果您正苦于以下问题:Python cattr.structure方法的具体用法?Python cattr.structure怎么用?Python cattr.structure使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cattr
的用法示例。
在下文中一共展示了cattr.structure方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse
# 需要导入模块: import cattr [as 别名]
# 或者: from cattr import structure [as 别名]
def parse(user_agent):
try:
return cattr.structure(_parser(user_agent), UserAgent)
except UnableToParse:
# If we were not able to parse the user agent, then we have two options, we can
# either raise an `UnknownUserAgentError` or we can return None to explicitly
# say that we opted not to parse this user agent. To determine which option we
# pick we'll match against a regex of UAs to ignore, if we match then we'll
# return a None to indicate to our caller that we couldn't parse this UA, but
# that it was an expected inability to parse. Otherwise we'll raise an
# `UnknownUserAgentError` to indicate that it as an unexpected inability to
# parse.
if _ignore_re.search(user_agent) is not None:
return None
raise UnknownUserAgentError from None
示例2: test_convert_from_dict
# 需要导入模块: import cattr [as 别名]
# 或者: from cattr import structure [as 别名]
def test_convert_from_dict():
config = yaml.safe_load(
"""
measure: progress
thresholds: [0.1, 0.3, 0.5]
min_lesson_length: 100
signal_smoothing: true
parameters:
param1: [0.0, 4.0, 6.0, 8.0]
"""
)
should_be_config = CurriculumSettings(
thresholds=[0.1, 0.3, 0.5],
min_lesson_length=100,
signal_smoothing=True,
measure=CurriculumSettings.MeasureType.PROGRESS,
parameters={"param1": [0.0, 4.0, 6.0, 8.0]},
)
assert cattr.structure(config, CurriculumSettings) == should_be_config
示例3: robotrequest_cb
# 需要导入模块: import cattr [as 别名]
# 或者: from cattr import structure [as 别名]
def robotrequest_cb(self, name: str, custom_res: Dict) -> None:
"""Process robotrequest messages."""
status = custom_res.get('status', {})
if status.get('data'):
# Convert message data to RequestFromRobot data class
robot_request = structure(status['data'], RequestFromRobot)
if self.state in self.conf.awaiting_who_completion_states and self.active_who:
if (robot_request.lgnum == self.active_who.lgnum
and robot_request.notifywhocompletion == self.active_who.who):
_LOGGER.info(
'Warehouse order %s was confirmed in EWM - robot is proceeding now',
self.active_who.who)
self.warehouseorder_confirmed()
if self.state in self.conf.awaiting_wht_completion_states and self.active_wht:
if (robot_request.lgnum == self.active_wht.lgnum
and robot_request.notifywhtcompletion == self.active_wht.tanum):
_LOGGER.info(
'Warehouse task %s was confirmed in EWM - robot is proceeding now',
self.active_wht.tanum)
self.warehousetask_confirmed()
示例4: get_reserved_warehouseorders
# 需要导入模块: import cattr [as 别名]
# 或者: from cattr import structure [as 别名]
def get_reserved_warehouseorders(self) -> List[WarehouseOrderIdent]:
"""Get reserved warehouse orders of reservations which are in process."""
reserved_whos: List[WarehouseOrderIdent] = []
# Get all CRs
cr_resp = self.list_all_cr()
if cr_resp:
for custom_res in cr_resp['items']:
# Continue if CR has no status
if not custom_res.get('status'):
continue
# Continue if CR is not in process
status = structure(custom_res.get('status'), OrderReservationStatus)
if status.status not in OrderReservationStatus.IN_PROCESS_STATUS:
continue
# Append warehouse order idents to list
for who in status.warehouseorders:
who_ident = WarehouseOrderIdent(lgnum=who.lgnum, who=who.who)
reserved_whos.append(who_ident)
return reserved_whos
示例5: _get_open_reservations_cb
# 需要导入模块: import cattr [as 别名]
# 或者: from cattr import structure [as 别名]
def _get_open_reservations_cb(self, name: str, custom_res: Dict) -> None:
"""Get an open reservation and determine the auctioneer which owns it."""
# Remove the current reservation from all entries in dictionary
with self._open_reservations_lock:
for res in self.open_reservations.values():
if name in res:
res.pop(name)
res_open = False
# Reservation is open if it does not have a status
if not custom_res.get('status'):
res_open = True
else:
# Evaluate status of reservation
status = structure(custom_res.get('status'), OrderReservationStatus)
if status.status in OrderReservationStatus.IN_PROCESS_STATUS:
res_open = True
if res_open:
owner_refs = custom_res['metadata'].get('ownerReferences')
if owner_refs is not None:
for owner_ref in owner_refs:
if owner_ref['kind'] == 'Auctioneer':
self._open_reservations[owner_ref['name']][name] = True
示例6: _load_ua_fixtures
# 需要导入模块: import cattr [as 别名]
# 或者: from cattr import structure [as 别名]
def _load_ua_fixtures(fixture_dir):
fixtures = os.listdir(fixture_dir)
for filename in fixtures:
with open(os.path.join(fixture_dir, filename), "r") as fp:
fixtures = yaml.safe_load(fp.read())
for fixture in fixtures:
ua = fixture.pop("ua")
result = fixture.pop("result")
expected = (
cattr.structure(result, UserAgent)
if isinstance(result, dict)
else result
)
assert fixture == {}
yield ua, expected
示例7: _get_instance
# 需要导入模块: import cattr [as 别名]
# 或者: from cattr import structure [as 别名]
def _get_instance(meta: Metadata):
"""
Instantiate an object from Metadata
"""
cls = import_string(meta.type_name)
return structure(meta.data, cls)
示例8: _render_object
# 需要导入模块: import cattr [as 别名]
# 或者: from cattr import structure [as 别名]
def _render_object(obj: Any, context) -> Any:
"""
Renders a attr annotated object. Will set non serializable attributes to none
"""
return structure(json.loads(ENV.from_string(
json.dumps(unstructure(obj), default=lambda o: None)
).render(**context).encode('utf-8')), type(obj))
示例9: check_and_structure
# 需要导入模块: import cattr [as 别名]
# 或者: from cattr import structure [as 别名]
def check_and_structure(key: str, value: Any, class_type: type) -> Any:
attr_fields_dict = attr.fields_dict(class_type)
if key not in attr_fields_dict:
raise TrainerConfigError(
f"The option {key} was specified in your YAML file for {class_type.__name__}, but is invalid."
)
# Apply cattr structure to the values
return cattr.structure(value, attr_fields_dict[key].type)
示例10: structure
# 需要导入模块: import cattr [as 别名]
# 或者: from cattr import structure [as 别名]
def structure(d: Mapping, t: type) -> Any:
"""
Helper method to structure a Dict of RewardSignalSettings class. Meant to be registered with
cattr.register_structure_hook() and called with cattr.structure(). This is needed to handle
the special Enum selection of RewardSignalSettings classes.
"""
if not isinstance(d, Mapping):
raise TrainerConfigError(f"Unsupported reward signal configuration {d}.")
d_final: Dict[RewardSignalType, RewardSignalSettings] = {}
for key, val in d.items():
enum_key = RewardSignalType(key)
t = enum_key.to_settings()
d_final[enum_key] = strict_to_cls(val, t)
return d_final
示例11: dict_to_defaultdict
# 需要导入模块: import cattr [as 别名]
# 或者: from cattr import structure [as 别名]
def dict_to_defaultdict(d: Dict, t: type) -> DefaultDict:
return collections.defaultdict(
TrainerSettings, cattr.structure(d, Dict[str, TrainerSettings])
)
示例12: from_dict
# 需要导入模块: import cattr [as 别名]
# 或者: from cattr import structure [as 别名]
def from_dict(import_dict: Dict[str, str]) -> "StatusMetaData":
return cattr.structure(import_dict, StatusMetaData)
示例13: validate
# 需要导入模块: import cattr [as 别名]
# 或者: from cattr import structure [as 别名]
def validate(self, data):
try:
return True, cattr.structure(data, self.model)
except ValueError as e:
return False, str(e)
except TypeError as e:
return False, str(e)
示例14: robotconfiguration_cb
# 需要导入模块: import cattr [as 别名]
# 或者: from cattr import structure [as 别名]
def robotconfiguration_cb(self, name: str, custom_res: Dict) -> None:
"""Process robot configuration CR."""
# Create new thread to check EWM resources if not running yet
if name not in self.running_robot_checks:
self.running_robot_checks[name] = True
self.executor.submit(
self.ewm_resource_check, name, structure(
custom_res['spec'], RobotConfigurationSpec))
示例15: warehouseorder_cb
# 需要导入模块: import cattr [as 别名]
# 或者: from cattr import structure [as 别名]
def warehouseorder_cb(self, name: str, spec: Dict) -> None:
"""Process warehouse order CRs."""
# Convert message data to WarehouseOrderCRDSpec type
who_crd_spec = structure(spec, WarehouseOrderCRDSpec)
self.update_warehouseorder(warehouseorder=who_crd_spec)