Untitled

mail@pastecode.io avatar
unknown
plain_text
23 days ago
2.0 kB
2
Indexable
Never
def get_data(self, tvals):
    # Check if Tally URL is configured
    if not self.env.company.tally_url:
        raise UserError(_('Please Configure the Tally URL'))

    # Send POST request to Tally URL
    try:
        req = requests.post(url=self.env.company.tally_url, data=tvals)
    except requests.exceptions.RequestException as e:
        raise UserError(_("Error while connecting to Tally: %s" % str(e)))

    # Ensure the response is valid
    if req.status_code != 200:
        raise UserError(_('Error: Received status code %s from Tally') % req.status_code)

    # Remove non-printable characters from response
    xml_content_clean = re.sub(r'[\x00-\x08\x0B-\x0C\x0E-\x1F]', '', req.text)

    # Further clean-up of XML content
    xml_tags = xml_content_clean.replace('', '').replace(''', 'quoteee').replace('&', 'andand').replace('|', '')

    # Log XML content size (for debugging)
    print(f"XML content size: {len(xml_tags)}")

    # Handle large XML response using iterparse for streaming
    try:
        # Use StringIO to wrap the cleaned XML string for streaming
        context = Et.iterparse(io.StringIO(xml_tags.strip()), events=("start", "end"))

        # Iterate through the elements to process them one by one
        for event, elem in context:
            if event == 'end':
                # Here you can process each element (example: logging or extracting info)
                # print(elem.tag, elem.text)

                # After processing, clear the element to free memory
                elem.clear()

        # Optional: If you need to return a fully parsed ElementTree object
        return Et.ElementTree(Et.fromstring(xml_tags.strip()))
    
    except Et.ParseError as e:
        raise UserError(_('XML Parsing Error: %s') % str(e))
    
    except MemoryError:
        raise UserError(_('Memory Error: Unable to process large XML response'))

    except Exception as e:
        raise UserError(_('Unexpected Error: %s') % str(e))
Leave a Comment