示例#1
0
def deserialize(resource: Union[str, Path, bytes],
                target_class: Optional[Type[T]] = None) -> Optional[T]:
    parser = XmlParser(context=XmlContext())
    obj = None

    if os.path.isfile(resource):
        resource = Path(resource)

    if isinstance(resource, str):
        obj = parser.from_string(resource, target_class)
    if isinstance(resource, Path):
        obj = parser.from_path(resource, target_class)
    if isinstance(resource, bytes):
        obj = parser.from_bytes(resource, target_class)

    if obj and hasattr(obj, 'complemento') and obj.complemento:
        complementos = __deserialize_complementos(obj)
        setattr(obj.complemento, 'any_element', complementos)

    return obj
示例#2
0
def parse(source, handler):
    parser = XmlParser(context=context, handler=handler)
    parser.from_bytes(source, Books)
示例#3
0
with open(fname, 'r') as fd:
    for url in fd.readlines():
        try:
            if url.startswith('#'):
                continue
            
            url = url.strip()

            r = requests.get(url, allow_redirects=True)

            # Upgrade to BTLx 1.1
            btlx_str = r.text.replace('Version="1.0"', 'Version="1.1"')

            # Validate BTLx against XSD
            # fromstring complains when we have UTF declaration like
            # `<?xml version="1.0" encoding="utf-8" ?>`, so we use bytes instead
            # https://stackoverflow.com/a/38244227
            btlx_bytes = bytes(bytearray(btlx_str, encoding='utf-8'))
            
            tree = objectify.fromstring(btlx_bytes)
            xmlschema.assertValid(tree)

            # Use xsd
            btlx = parser.from_bytes(btlx_bytes, Btlx)

            print('✔️  {}'.format(url))
        except Exception as e:
            traceback.print_exc()
            print('❌  {}'.format(url))
示例#4
0
class Application(SIPApplication):
    def __init__(self, *, config: Configuration) -> None:
        self.config = config

        self.serializer = XmlSerializer(config=SerializerConfig(
            pretty_print=False))
        self.parser = XmlParser(context=XmlContext())
        self.requests: WeakValueDictionary[str,
                                           Future] = WeakValueDictionary({})
        super().__init__()

    def start(self):
        notification_center = NotificationCenter()
        notification_center.add_observer(self, name='SIPEngineGotMessage')
        notification_center.add_observer(self, name='SIPMessageDidSucceed')
        notification_center.add_observer(self, name='SIPMessageDidFail')
        notification_center.add_observer(self, name='SIPApplicationDidStart')
        super().start(MemoryStorage())

    async def send_request(self, arc_name: str, scaip_request: ScaipRequest):
        logger.info(f"send_request to {arc_name}: {scaip_request}")

        config = self.config
        arc_config = config.get_arc_config(arc_name)

        if not arc_config:
            raise ValueError(f"no configuration found for ARC {arc_name}")

        xml_model = scaip_request.to_xml_model()
        xml_str = self.serializer.render(xml_model)

        result = self.new_result_future(scaip_request.reference)
        if scaip_request.caller_id.startswith(
                "sip") and scaip_request.caller_id != "sip:":
            caller_id = URI(scaip_request.caller_id)
            sender = SIPURI(user=caller_id.user,
                            host=caller_id.host,
                            port=caller_id.port)
        else:
            sender = self.get_user_agent_uri()

        receiver = SIPURI(user=arc_config.username,
                          host=arc_config.hostname,
                          port=arc_config.port)
        message = Message(FromHeader(sender), ToHeader(receiver),
                          RouteHeader(receiver), 'application/scaip+xml',
                          xml_str)
        message.send()
        logger.info(f"sent message: {xml_str}")

        scaip_response = await result

        logger.info(f"received response: {scaip_response}")

        return scaip_response

    def new_result_future(self, reference: str) -> Future:
        loop = asyncio.get_running_loop()
        result = loop.create_future()
        self.requests[reference] = result
        return result

    def get_user_agent_uri(self) -> SIPURI:
        sip_config = self.config.sip
        return SIPURI(user=sip_config.username,
                      host=sip_config.hostname,
                      port=sip_config.port)

    def _NH_SIPApplicationDidStart(self, notification):
        logger.info("SIPApplicationDidStart")

    def _NH_SIPMessageDidSucceed(self, notification):
        logger.info("SIPMessageDidSucceed")

    def _NH_SIPMessageDidFail(self, notification):
        logger.info("SIPMessageDidFail")

        message = notification.sender
        xml_model = self.parser.from_bytes(message.body, Mrq)

        result = self.requests.get(xml_model.ref, None)

        if result:
            # TODO: return proper error
            result.set_exception(
                HTTPException(status_code=500, detail="SIPMessageDidFail"))

    def _NH_SIPEngineGotMessage(self, notification):
        logger.info("SIPEngineGotMessage")
        logger.info(f"got XML: {notification.data.body}")
        xml_model = self.parser.from_bytes(notification.data.body, Mrs)
        scaip_response = ScaipResponse.from_xml_model(xml_model)

        result = self.requests.get(xml_model.ref, None)

        if result:
            result.set_result(scaip_response)
示例#5
0
def CreateFromDocument(document):
    parser = XmlParser(config=ParserConfig(fail_on_unknown_properties=True))
    if isinstance(document, str):
        return parser.from_string(document, ismrmrdHeader)
    return parser.from_bytes(document, ismrmrdHeader)