Untitled

mail@pastecode.io avatar
unknown
plain_text
24 days ago
1.8 kB
2
Indexable
Never
import requests
import re
import xml.etree.ElementTree as Et
import io
from odoo.exceptions import UserError

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)}")

    # Stream XML parsing to prevent memory overload
    try:
        # Create a StringIO object from the cleaned XML string
        xml_stream = io.StringIO(xml_tags.strip())

        # Use iterparse to process the XML in chunks
        context = Et.iterparse(xml_stream, events=("start", "end"))
        for event, elem in context:
            # Process each element
            print(f"Processing element: {elem.tag}")
            # Once done with the element, clear it to free memory
            elem.clear()

    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'))
    
    return True
Leave a Comment