Как отправить вложение через пакет Zeep в Python для SOAP веб-сервисов? - PullRequest
0 голосов
/ 13 июня 2019

Я пытаюсь отправить вложение через Zeep-клиент на мыльный веб-сервис.

Я пытался использовать класс-оболочку TransportWithAttach, на который ссылались в аналогичных предыдущих вопросах, таких как:

class TransportWithAttach(Transport):
    """Transport with attachment"""

    def __init__(self, cache=None, timeout=300, operation_timeout=None,
                 session=None):
        self.attachments = {}
        patch_things()
        super(TransportWithAttach, self).__init__(
            cache=cache, timeout=timeout, operation_timeout=operation_timeout,
            session=session)

    def post_xml(self, address, envelope, headers):
        # Search for values that startswith FILETAG
        filetags = envelope.xpath(
            "//*[starts-with(text(), '{}')]".format(FILETAG))
        # if there is some attached file we set the attachments
        print('filetags -- ', filetags)
        print('envelope -- ', envelope)
        print('headers -- ', headers)
        #if filetags:
        #    message = self.set_attachs(filetags, envelope, headers)
        # else just the envelope
        #else:
        #    message = etree_to_string(envelope)
        message = self.set_attachs(envelope, headers)
        print('message returned with attach --', message)
        # post the data.
        return self.post(address, message, headers)

    def set_attachs(self, envelope, headers):
        """Set mtom attachs and return the right envelope"""
        # let's get the mtom multi part.
        mtom_part = get_multipart()
        # let's set xop:Include for al the files.
        # we need to do this before get the envelope part.
        #files = [set_attachnode(f) for f in filetags]
        # get the envelope part.
        env_part = get_envelopepart(envelope)
        # attach the env_part to the multipart.
        mtom_part.attach(env_part)
        # for each filename in files.
        #for cid in files:
            # attach the filepart to the multipart.
        mtom_part.attach(self.get_attachpart())
        # some other stuff.
        bound = '--%s'.format(mtom_part.get_boundary())
        marray = mtom_part.as_string().split(bound)
        mtombody = bound
        mtombody += bound.join(marray[1:])
        mtom_part.add_header("Content-Length", str(len(mtombody)))
        headers.update(dict(mtom_part.items()))
        message = mtom_part.as_string().split('\n\n', 1)[1]
        message = message.replace('\n', '\r\n', 5)
        # return the messag for the post.
        return message

    def get_attachpart(self):
        """The file part"""
        #attach = self.attachments[cid]
        part = MIMEBase("text", "plain")
        part.set_param('charset', 'us-ascii')
        part.set_param('name', 'test.txt')
        part['Content-Transfer-Encoding'] = "7bit"
        part['Content-ID'] = "<test.txt>"
        part['Content-Disposition'] = 'attachment; name="test.txt"; filename="test.txt"'
        by = open("test.txt", "rb").read()
        #by = f.read()
        part.set_payload(by)
        del part['mime-version']
        return part

Это должноотправить файл в веб-службу SOAP, но вместо этого я получаю сообщение об ошибке content is not allowed in prolog.

Есть ли в python пакет, который предоставляет встроенные методы для отправки файла через SOAP API?

...