From f5daae30c2c4de69c725cff0ec24fa55512f37c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Marcos=20Ferreira?= Date: Wed, 12 Apr 2023 15:45:01 -0300 Subject: [PATCH 1/2] =?UTF-8?q?[WIP]=20valida=C3=A7=C3=A3o=20de=20layout?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- nfselib/barueri/rps.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nfselib/barueri/rps.py b/nfselib/barueri/rps.py index 3c322b4..46abdcc 100644 --- a/nfselib/barueri/rps.py +++ b/nfselib/barueri/rps.py @@ -10,10 +10,10 @@ class RPS(Arquivo): class RegistroTipo1(Registro): campos = [ CampoPosicional("TipoRegistro", "1", True, "NUM", 1, 1, 1), - CampoPosicional("InscricaoContribuinte", None, True, "NUM", 14, 2, 15), - CampoPosicional("VersaoLayout", "PMB002", True, "NUM", 5, 16, 20), - CampoPosicional("IdentificacaoRemessaContribuinte", None, True, "NUM", 12, 21, 32), - CampoPosicional("CaracterFimLinha", "\r\n", True, "ALFA", 2, 33, 34), + CampoPosicional("InscricaoContribuinte", None, True, "ALFA", 7, 2, 8), + CampoPosicional("VersaoLayout", "PMB002", True, "NUM", 6, 9, 14), + CampoPosicional("IdentificacaoRemessaContribuinte", None, True, "NUM", 11, 15, 25), + CampoPosicional("CaracterFimLinha", "\r\n", True, "ALFA", 1, 26, 26), ] From 6d423db40438f56a813aea45c925fe4d8d5e1beb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Marcos=20Ferreira?= Date: Thu, 13 Apr 2023 04:04:41 -0300 Subject: [PATCH 2/2] [ADD] nfselib.barueri [ADD] Enviar Arquivo and Namespaces [ADD] scripts folder [ADD] nfselib.barueri --- .../ConsultarNFeRecebidaCompetencia.py | 1371 ++++++++++++++++ nfselib/barueri/ConsultarNFeRecebidaNumero.py | 1341 ++++++++++++++++ .../barueri/ConsultarNFeRecebidaPeriodo.py | 1391 ++++++++++++++++ nfselib/barueri/NFeLoteBaixarArquivo.py | 1348 ++++++++++++++++ nfselib/barueri/NFeLoteEnviarArquivo.py | 1415 +++++++++++++++++ nfselib/barueri/NFeLoteListarArquivo.py | 1396 ++++++++++++++++ nfselib/barueri/NFeLoteStatusArquivo.py | 1347 ++++++++++++++++ nfselib/barueri/exportador.py | 1 - nfselib/barueri/generatedsnamespaces.py | 18 + .../ConsultaNFeRecebidaCompetencia.v1.xsd | 25 + .../barueri/ConsultaNFeRecebidaNumero.v1.xsd | 20 + .../barueri/ConsultaNFeRecebidaPeriodo.v1.xsd | 30 + schemas/barueri/NFeLoteBaixarArquivo.v1.xsd | 24 + schemas/barueri/NFeLoteEnviarArquivo.v1.xsd | 34 + schemas/barueri/NFeLoteListarArquivos.v1.xsd | 44 + schemas/barueri/NFeLoteStatusArquivo.v1.xsd | 24 + scripts/README.md | 1 + scripts/generate.sh | 2 + 18 files changed, 9831 insertions(+), 1 deletion(-) create mode 100644 nfselib/barueri/ConsultarNFeRecebidaCompetencia.py create mode 100644 nfselib/barueri/ConsultarNFeRecebidaNumero.py create mode 100644 nfselib/barueri/ConsultarNFeRecebidaPeriodo.py create mode 100644 nfselib/barueri/NFeLoteBaixarArquivo.py create mode 100644 nfselib/barueri/NFeLoteEnviarArquivo.py create mode 100644 nfselib/barueri/NFeLoteListarArquivo.py create mode 100644 nfselib/barueri/NFeLoteStatusArquivo.py create mode 100644 nfselib/barueri/generatedsnamespaces.py create mode 100644 schemas/barueri/ConsultaNFeRecebidaCompetencia.v1.xsd create mode 100644 schemas/barueri/ConsultaNFeRecebidaNumero.v1.xsd create mode 100644 schemas/barueri/ConsultaNFeRecebidaPeriodo.v1.xsd create mode 100644 schemas/barueri/NFeLoteBaixarArquivo.v1.xsd create mode 100644 schemas/barueri/NFeLoteEnviarArquivo.v1.xsd create mode 100644 schemas/barueri/NFeLoteListarArquivos.v1.xsd create mode 100644 schemas/barueri/NFeLoteStatusArquivo.v1.xsd create mode 100644 scripts/README.md create mode 100644 scripts/generate.sh diff --git a/nfselib/barueri/ConsultarNFeRecebidaCompetencia.py b/nfselib/barueri/ConsultarNFeRecebidaCompetencia.py new file mode 100644 index 0000000..744e022 --- /dev/null +++ b/nfselib/barueri/ConsultarNFeRecebidaCompetencia.py @@ -0,0 +1,1371 @@ +#TODO + +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# +# Generated Thu Apr 13 03:39:56 2023 by generateDS.py version 2.41.3. +# Python 3.8.10 (default, Mar 13 2023, 10:26:41) [GCC 9.4.0] +# +# Command line options: +# ('-o', 'ConsultarNFeRecebidaCompetencia.py') +# +# Command line arguments: +# ../../schemas/barueri/ConsultaNFeRecebidaCompetencia.v1.xsd +# +# Command line: +# /home/andre/.local/bin/generateDS -o "ConsultarNFeRecebidaCompetencia.py" ../../schemas/barueri/ConsultaNFeRecebidaCompetencia.v1.xsd +# +# Current working directory (os.getcwd()): +# barueri +# + +import sys +try: + ModulenotfoundExp_ = ModuleNotFoundError +except NameError: + ModulenotfoundExp_ = ImportError +from six.moves import zip_longest +import os +import re as re_ +import base64 +import datetime as datetime_ +import decimal as decimal_ +from lxml import etree as etree_ + + +Validate_simpletypes_ = True +SaveElementTreeNode = True +TagNamePrefix = "" +if sys.version_info.major == 2: + BaseStrType_ = basestring +else: + BaseStrType_ = str + + +def parsexml_(infile, parser=None, **kwargs): + if parser is None: + # Use the lxml ElementTree compatible parser so that, e.g., + # we ignore comments. + try: + parser = etree_.ETCompatXMLParser() + except AttributeError: + # fallback to xml.etree + parser = etree_.XMLParser() + try: + if isinstance(infile, os.PathLike): + infile = os.path.join(infile) + except AttributeError: + pass + doc = etree_.parse(infile, parser=parser, **kwargs) + return doc + +def parsexmlstring_(instring, parser=None, **kwargs): + if parser is None: + # Use the lxml ElementTree compatible parser so that, e.g., + # we ignore comments. + try: + parser = etree_.ETCompatXMLParser() + except AttributeError: + # fallback to xml.etree + parser = etree_.XMLParser() + element = etree_.fromstring(instring, parser=parser, **kwargs) + return element + +# +# Namespace prefix definition table (and other attributes, too) +# +# The module generatedsnamespaces, if it is importable, must contain +# a dictionary named GeneratedsNamespaceDefs. This Python dictionary +# should map element type names (strings) to XML schema namespace prefix +# definitions. The export method for any class for which there is +# a namespace prefix definition, will export that definition in the +# XML representation of that element. See the export method of +# any generated element type class for an example of the use of this +# table. +# A sample table is: +# +# # File: generatedsnamespaces.py +# +# GenerateDSNamespaceDefs = { +# "ElementtypeA": "http://www.xxx.com/namespaceA", +# "ElementtypeB": "http://www.xxx.com/namespaceB", +# } +# +# Additionally, the generatedsnamespaces module can contain a python +# dictionary named GenerateDSNamespaceTypePrefixes that associates element +# types with the namespace prefixes that are to be added to the +# "xsi:type" attribute value. See the _exportAttributes method of +# any generated element type and the generation of "xsi:type" for an +# example of the use of this table. +# An example table: +# +# # File: generatedsnamespaces.py +# +# GenerateDSNamespaceTypePrefixes = { +# "ElementtypeC": "aaa:", +# "ElementtypeD": "bbb:", +# } +# + +try: + from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ +except ModulenotfoundExp_ : + GenerateDSNamespaceDefs_ = {} +try: + from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ +except ModulenotfoundExp_ : + GenerateDSNamespaceTypePrefixes_ = {} + +# +# You can replace the following class definition by defining an +# importable module named "generatedscollector" containing a class +# named "GdsCollector". See the default class definition below for +# clues about the possible content of that class. +# +try: + from generatedscollector import GdsCollector as GdsCollector_ +except ModulenotfoundExp_ : + + class GdsCollector_(object): + + def __init__(self, messages=None): + if messages is None: + self.messages = [] + else: + self.messages = messages + + def add_message(self, msg): + self.messages.append(msg) + + def get_messages(self): + return self.messages + + def clear_messages(self): + self.messages = [] + + def print_messages(self): + for msg in self.messages: + print("Warning: {}".format(msg)) + + def write_messages(self, outstream): + for msg in self.messages: + outstream.write("Warning: {}\n".format(msg)) + + +# +# The super-class for enum types +# + +try: + from enum import Enum +except ModulenotfoundExp_ : + Enum = object + +# +# The root super-class for element type classes +# +# Calls to the methods in these classes are generated by generateDS.py. +# You can replace these methods by re-implementing the following class +# in a module named generatedssuper.py. + +try: + from generatedssuper import GeneratedsSuper +except ModulenotfoundExp_ as exp: + try: + from generatedssupersuper import GeneratedsSuperSuper + except ModulenotfoundExp_ as exp: + class GeneratedsSuperSuper(object): + pass + + class GeneratedsSuper(GeneratedsSuperSuper): + __hash__ = object.__hash__ + tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') + class _FixedOffsetTZ(datetime_.tzinfo): + def __init__(self, offset, name): + self.__offset = datetime_.timedelta(minutes=offset) + self.__name = name + def utcoffset(self, dt): + return self.__offset + def tzname(self, dt): + return self.__name + def dst(self, dt): + return None + def __str__(self): + settings = { + 'str_pretty_print': True, + 'str_indent_level': 0, + 'str_namespaceprefix': '', + 'str_name': self.__class__.__name__, + 'str_namespacedefs': '', + } + for n in settings: + if hasattr(self, n): + settings[n] = getattr(self, n) + if sys.version_info.major == 2: + from StringIO import StringIO + else: + from io import StringIO + output = StringIO() + self.export( + output, + settings['str_indent_level'], + pretty_print=settings['str_pretty_print'], + namespaceprefix_=settings['str_namespaceprefix'], + name_=settings['str_name'], + namespacedef_=settings['str_namespacedefs'] + ) + strval = output.getvalue() + output.close() + return strval + def gds_format_string(self, input_data, input_name=''): + return input_data + def gds_parse_string(self, input_data, node=None, input_name=''): + return input_data + def gds_validate_string(self, input_data, node=None, input_name=''): + if not input_data: + return '' + else: + return input_data + def gds_format_base64(self, input_data, input_name=''): + return base64.b64encode(input_data).decode('ascii') + def gds_validate_base64(self, input_data, node=None, input_name=''): + return input_data + def gds_format_integer(self, input_data, input_name=''): + return '%d' % int(input_data) + def gds_parse_integer(self, input_data, node=None, input_name=''): + try: + ival = int(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires integer value: %s' % exp) + return ival + def gds_validate_integer(self, input_data, node=None, input_name=''): + try: + value = int(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires integer value') + return value + def gds_format_integer_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_integer_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + int(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of integer values') + return values + def gds_format_float(self, input_data, input_name=''): + return ('%.15f' % float(input_data)).rstrip('0') + def gds_parse_float(self, input_data, node=None, input_name=''): + try: + fval_ = float(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires float or double value: %s' % exp) + return fval_ + def gds_validate_float(self, input_data, node=None, input_name=''): + try: + value = float(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires float value') + return value + def gds_format_float_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_float_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + float(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of float values') + return values + def gds_format_decimal(self, input_data, input_name=''): + return_value = '%s' % input_data + if '.' in return_value: + return_value = return_value.rstrip('0') + if return_value.endswith('.'): + return_value = return_value.rstrip('.') + return return_value + def gds_parse_decimal(self, input_data, node=None, input_name=''): + try: + decimal_value = decimal_.Decimal(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires decimal value') + return decimal_value + def gds_validate_decimal(self, input_data, node=None, input_name=''): + try: + value = decimal_.Decimal(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires decimal value') + return value + def gds_format_decimal_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return ' '.join([self.gds_format_decimal(item) for item in input_data]) + def gds_validate_decimal_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + decimal_.Decimal(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of decimal values') + return values + def gds_format_double(self, input_data, input_name=''): + return '%s' % input_data + def gds_parse_double(self, input_data, node=None, input_name=''): + try: + fval_ = float(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires double or float value: %s' % exp) + return fval_ + def gds_validate_double(self, input_data, node=None, input_name=''): + try: + value = float(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires double or float value') + return value + def gds_format_double_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_double_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + float(value) + except (TypeError, ValueError): + raise_parse_error( + node, 'Requires sequence of double or float values') + return values + def gds_format_boolean(self, input_data, input_name=''): + return ('%s' % input_data).lower() + def gds_parse_boolean(self, input_data, node=None, input_name=''): + input_data = input_data.strip() + if input_data in ('true', '1'): + bval = True + elif input_data in ('false', '0'): + bval = False + else: + raise_parse_error(node, 'Requires boolean value') + return bval + def gds_validate_boolean(self, input_data, node=None, input_name=''): + if input_data not in (True, 1, False, 0, ): + raise_parse_error( + node, + 'Requires boolean value ' + '(one of True, 1, False, 0)') + return input_data + def gds_format_boolean_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_boolean_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + value = self.gds_parse_boolean(value, node, input_name) + if value not in (True, 1, False, 0, ): + raise_parse_error( + node, + 'Requires sequence of boolean values ' + '(one of True, 1, False, 0)') + return values + def gds_validate_datetime(self, input_data, node=None, input_name=''): + return input_data + def gds_format_datetime(self, input_data, input_name=''): + if input_data.microsecond == 0: + _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( + input_data.year, + input_data.month, + input_data.day, + input_data.hour, + input_data.minute, + input_data.second, + ) + else: + _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( + input_data.year, + input_data.month, + input_data.day, + input_data.hour, + input_data.minute, + input_data.second, + ('%f' % (float(input_data.microsecond) / 1000000))[2:], + ) + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) + return _svalue + @classmethod + def gds_parse_datetime(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + time_parts = input_data.split('.') + if len(time_parts) > 1: + micro_seconds = int(float('0.' + time_parts[1]) * 1000000) + input_data = '%s.%s' % ( + time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) + dt = datetime_.datetime.strptime( + input_data, '%Y-%m-%dT%H:%M:%S.%f') + else: + dt = datetime_.datetime.strptime( + input_data, '%Y-%m-%dT%H:%M:%S') + dt = dt.replace(tzinfo=tz) + return dt + def gds_validate_date(self, input_data, node=None, input_name=''): + return input_data + def gds_format_date(self, input_data, input_name=''): + _svalue = '%04d-%02d-%02d' % ( + input_data.year, + input_data.month, + input_data.day, + ) + try: + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format( + hours, minutes) + except AttributeError: + pass + return _svalue + @classmethod + def gds_parse_date(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') + dt = dt.replace(tzinfo=tz) + return dt.date() + def gds_validate_time(self, input_data, node=None, input_name=''): + return input_data + def gds_format_time(self, input_data, input_name=''): + if input_data.microsecond == 0: + _svalue = '%02d:%02d:%02d' % ( + input_data.hour, + input_data.minute, + input_data.second, + ) + else: + _svalue = '%02d:%02d:%02d.%s' % ( + input_data.hour, + input_data.minute, + input_data.second, + ('%f' % (float(input_data.microsecond) / 1000000))[2:], + ) + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) + return _svalue + def gds_validate_simple_patterns(self, patterns, target): + # pat is a list of lists of strings/patterns. + # The target value must match at least one of the patterns + # in order for the test to succeed. + found1 = True + target = str(target) + for patterns1 in patterns: + found2 = False + for patterns2 in patterns1: + mo = re_.search(patterns2, target) + if mo is not None and len(mo.group(0)) == len(target): + found2 = True + break + if not found2: + found1 = False + break + return found1 + @classmethod + def gds_parse_time(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + if len(input_data.split('.')) > 1: + dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') + else: + dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') + dt = dt.replace(tzinfo=tz) + return dt.time() + def gds_check_cardinality_( + self, value, input_name, + min_occurs=0, max_occurs=1, required=None): + if value is None: + length = 0 + elif isinstance(value, list): + length = len(value) + else: + length = 1 + if required is not None : + if required and length < 1: + self.gds_collector_.add_message( + "Required value {}{} is missing".format( + input_name, self.gds_get_node_lineno_())) + if length < min_occurs: + self.gds_collector_.add_message( + "Number of values for {}{} is below " + "the minimum allowed, " + "expected at least {}, found {}".format( + input_name, self.gds_get_node_lineno_(), + min_occurs, length)) + elif length > max_occurs: + self.gds_collector_.add_message( + "Number of values for {}{} is above " + "the maximum allowed, " + "expected at most {}, found {}".format( + input_name, self.gds_get_node_lineno_(), + max_occurs, length)) + def gds_validate_builtin_ST_( + self, validator, value, input_name, + min_occurs=None, max_occurs=None, required=None): + if value is not None: + try: + validator(value, input_name=input_name) + except GDSParseError as parse_error: + self.gds_collector_.add_message(str(parse_error)) + def gds_validate_defined_ST_( + self, validator, value, input_name, + min_occurs=None, max_occurs=None, required=None): + if value is not None: + try: + validator(value) + except GDSParseError as parse_error: + self.gds_collector_.add_message(str(parse_error)) + def gds_str_lower(self, instring): + return instring.lower() + def get_path_(self, node): + path_list = [] + self.get_path_list_(node, path_list) + path_list.reverse() + path = '/'.join(path_list) + return path + Tag_strip_pattern_ = re_.compile(r'\{.*\}') + def get_path_list_(self, node, path_list): + if node is None: + return + tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) + if tag: + path_list.append(tag) + self.get_path_list_(node.getparent(), path_list) + def get_class_obj_(self, node, default_class=None): + class_obj1 = default_class + if 'xsi' in node.nsmap: + classname = node.get('{%s}type' % node.nsmap['xsi']) + if classname is not None: + names = classname.split(':') + if len(names) == 2: + classname = names[1] + class_obj2 = globals().get(classname) + if class_obj2 is not None: + class_obj1 = class_obj2 + return class_obj1 + def gds_build_any(self, node, type_name=None): + # provide default value in case option --disable-xml is used. + content = "" + content = etree_.tostring(node, encoding="unicode") + return content + @classmethod + def gds_reverse_node_mapping(cls, mapping): + return dict(((v, k) for k, v in mapping.items())) + @staticmethod + def gds_encode(instring): + if sys.version_info.major == 2: + if ExternalEncoding: + encoding = ExternalEncoding + else: + encoding = 'utf-8' + return instring.encode(encoding) + else: + return instring + @staticmethod + def convert_unicode(instring): + if isinstance(instring, str): + result = quote_xml(instring) + elif sys.version_info.major == 2 and isinstance(instring, unicode): + result = quote_xml(instring).encode('utf8') + else: + result = GeneratedsSuper.gds_encode(str(instring)) + return result + def __eq__(self, other): + def excl_select_objs_(obj): + return (obj[0] != 'parent_object_' and + obj[0] != 'gds_collector_') + if type(self) != type(other): + return False + return all(x == y for x, y in zip_longest( + filter(excl_select_objs_, self.__dict__.items()), + filter(excl_select_objs_, other.__dict__.items()))) + def __ne__(self, other): + return not self.__eq__(other) + # Django ETL transform hooks. + def gds_djo_etl_transform(self): + pass + def gds_djo_etl_transform_db_obj(self, dbobj): + pass + # SQLAlchemy ETL transform hooks. + def gds_sqa_etl_transform(self): + return 0, None + def gds_sqa_etl_transform_db_obj(self, dbobj): + pass + def gds_get_node_lineno_(self): + if (hasattr(self, "gds_elementtree_node_") and + self.gds_elementtree_node_ is not None): + return ' near line {}'.format( + self.gds_elementtree_node_.sourceline) + else: + return "" + + + def getSubclassFromModule_(module, class_): + '''Get the subclass of a class from a specific module.''' + name = class_.__name__ + 'Sub' + if hasattr(module, name): + return getattr(module, name) + else: + return None + + +# +# If you have installed IPython you can uncomment and use the following. +# IPython is available from http://ipython.scipy.org/. +# + +## from IPython.Shell import IPShellEmbed +## args = '' +## ipshell = IPShellEmbed(args, +## banner = 'Dropping into IPython', +## exit_msg = 'Leaving Interpreter, back to program.') + +# Then use the following line where and when you want to drop into the +# IPython shell: +# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') + +# +# Globals +# + +ExternalEncoding = '' +# Set this to false in order to deactivate during export, the use of +# name space prefixes captured from the input document. +UseCapturedNS_ = True +CapturedNsmap_ = {} +Tag_pattern_ = re_.compile(r'({.*})?(.*)') +String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") +Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') +CDATA_pattern_ = re_.compile(r"", re_.DOTALL) + +# Change this to redirect the generated superclass module to use a +# specific subclass module. +CurrentSubclassModule_ = None + +# +# Support/utility functions. +# + + +def showIndent(outfile, level, pretty_print=True): + if pretty_print: + for idx in range(level): + outfile.write(' ') + + +def quote_xml(inStr): + "Escape markup chars, but do not modify CDATA sections." + if not inStr: + return '' + s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) + s2 = '' + pos = 0 + matchobjects = CDATA_pattern_.finditer(s1) + for mo in matchobjects: + s3 = s1[pos:mo.start()] + s2 += quote_xml_aux(s3) + s2 += s1[mo.start():mo.end()] + pos = mo.end() + s3 = s1[pos:] + s2 += quote_xml_aux(s3) + return s2 + + +def quote_xml_aux(inStr): + s1 = inStr.replace('&', '&') + s1 = s1.replace('<', '<') + s1 = s1.replace('>', '>') + return s1 + + +def quote_attrib(inStr): + s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) + s1 = s1.replace('&', '&') + s1 = s1.replace('<', '<') + s1 = s1.replace('>', '>') + s1 = s1.replace('\n', ' ') + if '"' in s1: + if "'" in s1: + s1 = '"%s"' % s1.replace('"', """) + else: + s1 = "'%s'" % s1 + else: + s1 = '"%s"' % s1 + return s1 + + +def quote_python(inStr): + s1 = inStr + if s1.find("'") == -1: + if s1.find('\n') == -1: + return "'%s'" % s1 + else: + return "'''%s'''" % s1 + else: + if s1.find('"') != -1: + s1 = s1.replace('"', '\\"') + if s1.find('\n') == -1: + return '"%s"' % s1 + else: + return '"""%s"""' % s1 + + +def get_all_text_(node): + if node.text is not None: + text = node.text + else: + text = '' + for child in node: + if child.tail is not None: + text += child.tail + return text + + +def find_attr_value_(attr_name, node): + attrs = node.attrib + attr_parts = attr_name.split(':') + value = None + if len(attr_parts) == 1: + value = attrs.get(attr_name) + elif len(attr_parts) == 2: + prefix, name = attr_parts + if prefix == 'xml': + namespace = 'http://www.w3.org/XML/1998/namespace' + else: + namespace = node.nsmap.get(prefix) + if namespace is not None: + value = attrs.get('{%s}%s' % (namespace, name, )) + return value + + +def encode_str_2_3(instr): + return instr + + +class GDSParseError(Exception): + pass + + +def raise_parse_error(node, msg): + if node is not None: + msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) + raise GDSParseError(msg) + + +class MixedContainer: + # Constants for category: + CategoryNone = 0 + CategoryText = 1 + CategorySimple = 2 + CategoryComplex = 3 + # Constants for content_type: + TypeNone = 0 + TypeText = 1 + TypeString = 2 + TypeInteger = 3 + TypeFloat = 4 + TypeDecimal = 5 + TypeDouble = 6 + TypeBoolean = 7 + TypeBase64 = 8 + def __init__(self, category, content_type, name, value): + self.category = category + self.content_type = content_type + self.name = name + self.value = value + def getCategory(self): + return self.category + def getContenttype(self, content_type): + return self.content_type + def getValue(self): + return self.value + def getName(self): + return self.name + def export(self, outfile, level, name, namespace, + pretty_print=True): + if self.category == MixedContainer.CategoryText: + # Prevent exporting empty content as empty lines. + if self.value.strip(): + outfile.write(self.value) + elif self.category == MixedContainer.CategorySimple: + self.exportSimple(outfile, level, name) + else: # category == MixedContainer.CategoryComplex + self.value.export( + outfile, level, namespace, name_=name, + pretty_print=pretty_print) + def exportSimple(self, outfile, level, name): + if self.content_type == MixedContainer.TypeString: + outfile.write('<%s>%s' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeInteger or \ + self.content_type == MixedContainer.TypeBoolean: + outfile.write('<%s>%d' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeFloat or \ + self.content_type == MixedContainer.TypeDecimal: + outfile.write('<%s>%f' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeDouble: + outfile.write('<%s>%g' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeBase64: + outfile.write('<%s>%s' % ( + self.name, + base64.b64encode(self.value), + self.name)) + def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): + if self.category == MixedContainer.CategoryText: + # Prevent exporting empty content as empty lines. + if self.value.strip(): + if len(element) > 0: + if element[-1].tail is None: + element[-1].tail = self.value + else: + element[-1].tail += self.value + else: + if element.text is None: + element.text = self.value + else: + element.text += self.value + elif self.category == MixedContainer.CategorySimple: + subelement = etree_.SubElement( + element, '%s' % self.name) + subelement.text = self.to_etree_simple() + else: # category == MixedContainer.CategoryComplex + self.value.to_etree(element) + def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): + if self.content_type == MixedContainer.TypeString: + text = self.value + elif (self.content_type == MixedContainer.TypeInteger or + self.content_type == MixedContainer.TypeBoolean): + text = '%d' % self.value + elif (self.content_type == MixedContainer.TypeFloat or + self.content_type == MixedContainer.TypeDecimal): + text = '%f' % self.value + elif self.content_type == MixedContainer.TypeDouble: + text = '%g' % self.value + elif self.content_type == MixedContainer.TypeBase64: + text = '%s' % base64.b64encode(self.value) + return text + def exportLiteral(self, outfile, level, name): + if self.category == MixedContainer.CategoryText: + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( + self.category, self.content_type, + self.name, self.value)) + elif self.category == MixedContainer.CategorySimple: + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( + self.category, self.content_type, + self.name, self.value)) + else: # category == MixedContainer.CategoryComplex + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s",\n' % ( + self.category, self.content_type, self.name,)) + self.value.exportLiteral(outfile, level + 1) + showIndent(outfile, level) + outfile.write(')\n') + + +class MemberSpec_(object): + def __init__(self, name='', data_type='', container=0, + optional=0, child_attrs=None, choice=None): + self.name = name + self.data_type = data_type + self.container = container + self.child_attrs = child_attrs + self.choice = choice + self.optional = optional + def set_name(self, name): self.name = name + def get_name(self): return self.name + def set_data_type(self, data_type): self.data_type = data_type + def get_data_type_chain(self): return self.data_type + def get_data_type(self): + if isinstance(self.data_type, list): + if len(self.data_type) > 0: + return self.data_type[-1] + else: + return 'xs:string' + else: + return self.data_type + def set_container(self, container): self.container = container + def get_container(self): return self.container + def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs + def get_child_attrs(self): return self.child_attrs + def set_choice(self, choice): self.choice = choice + def get_choice(self): return self.choice + def set_optional(self, optional): self.optional = optional + def get_optional(self): return self.optional + + +def _cast(typ, value): + if typ is None or value is None: + return value + return typ(value) + +# +# Data representation classes. +# + + +class NFeRecebidaCompetencia(GeneratedsSuper): + """Competencia -- M + ê + s de Compet + ê + ncia que Nota refere-se (AAAAMM). + CPFCNPJPrestador -- CNPJ/CPF do Prestador do Servi + ç + o, ou seja, aquele que emitiu a nota ao Tomador + Pagina -- N + ú + mero da pagina que deseja consulta, caso a pesquisa excede o n + ú + mero de registros permitido o resultado + é + disponibilizado em p + á + ginas + + """ + __hash__ = GeneratedsSuper.__hash__ + subclass = None + superclass = None + def __init__(self, CPFCNPJTomador=None, Competencia=None, CPFCNPJPrestador=None, Pagina=None, gds_collector_=None, **kwargs_): + self.gds_collector_ = gds_collector_ + self.gds_elementtree_node_ = None + self.original_tagname_ = None + self.parent_object_ = kwargs_.get('parent_object_') + self.ns_prefix_ = None + self.CPFCNPJTomador = CPFCNPJTomador + self.CPFCNPJTomador_nsprefix_ = None + self.Competencia = Competencia + self.Competencia_nsprefix_ = None + self.CPFCNPJPrestador = CPFCNPJPrestador + self.CPFCNPJPrestador_nsprefix_ = None + self.Pagina = Pagina + self.Pagina_nsprefix_ = None + def factory(*args_, **kwargs_): + if CurrentSubclassModule_ is not None: + subclass = getSubclassFromModule_( + CurrentSubclassModule_, NFeRecebidaCompetencia) + if subclass is not None: + return subclass(*args_, **kwargs_) + if NFeRecebidaCompetencia.subclass: + return NFeRecebidaCompetencia.subclass(*args_, **kwargs_) + else: + return NFeRecebidaCompetencia(*args_, **kwargs_) + factory = staticmethod(factory) + def get_ns_prefix_(self): + return self.ns_prefix_ + def set_ns_prefix_(self, ns_prefix): + self.ns_prefix_ = ns_prefix + def get_CPFCNPJTomador(self): + return self.CPFCNPJTomador + def set_CPFCNPJTomador(self, CPFCNPJTomador): + self.CPFCNPJTomador = CPFCNPJTomador + def get_Competencia(self): + return self.Competencia + def set_Competencia(self, Competencia): + self.Competencia = Competencia + def get_CPFCNPJPrestador(self): + return self.CPFCNPJPrestador + def set_CPFCNPJPrestador(self, CPFCNPJPrestador): + self.CPFCNPJPrestador = CPFCNPJPrestador + def get_Pagina(self): + return self.Pagina + def set_Pagina(self, Pagina): + self.Pagina = Pagina + def _hasContent(self): + if ( + self.CPFCNPJTomador is not None or + self.Competencia is not None or + self.CPFCNPJPrestador is not None or + self.Pagina is not None + ): + return True + else: + return False + def export(self, outfile, level, namespaceprefix_='', namespacedef_=' xmlns:None="http://www.barueri.sp.gov.br/nfe" ', name_='NFeRecebidaCompetencia', pretty_print=True): + imported_ns_def_ = GenerateDSNamespaceDefs_.get('NFeRecebidaCompetencia') + if imported_ns_def_ is not None: + namespacedef_ = imported_ns_def_ + if pretty_print: + eol_ = '\n' + else: + eol_ = '' + if self.original_tagname_ is not None and name_ == 'NFeRecebidaCompetencia': + name_ = self.original_tagname_ + if UseCapturedNS_ and self.ns_prefix_: + namespaceprefix_ = self.ns_prefix_ + ':' + showIndent(outfile, level, pretty_print) + outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) + already_processed = set() + self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='NFeRecebidaCompetencia') + if self._hasContent(): + outfile.write('>%s' % (eol_, )) + self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='NFeRecebidaCompetencia', pretty_print=pretty_print) + showIndent(outfile, level, pretty_print) + outfile.write('%s' % (namespaceprefix_, name_, eol_)) + else: + outfile.write('/>%s' % (eol_, )) + def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='NFeRecebidaCompetencia'): + pass + def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_=' xmlns:None="http://www.barueri.sp.gov.br/nfe" ', name_='NFeRecebidaCompetencia', fromsubclass_=False, pretty_print=True): + if pretty_print: + eol_ = '\n' + else: + eol_ = '' + if self.CPFCNPJTomador is not None: + namespaceprefix_ = self.CPFCNPJTomador_nsprefix_ + ':' if (UseCapturedNS_ and self.CPFCNPJTomador_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sCPFCNPJTomador>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CPFCNPJTomador), input_name='CPFCNPJTomador')), namespaceprefix_ , eol_)) + if self.Competencia is not None: + namespaceprefix_ = self.Competencia_nsprefix_ + ':' if (UseCapturedNS_ and self.Competencia_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sCompetencia>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Competencia), input_name='Competencia')), namespaceprefix_ , eol_)) + if self.CPFCNPJPrestador is not None: + namespaceprefix_ = self.CPFCNPJPrestador_nsprefix_ + ':' if (UseCapturedNS_ and self.CPFCNPJPrestador_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sCPFCNPJPrestador>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CPFCNPJPrestador), input_name='CPFCNPJPrestador')), namespaceprefix_ , eol_)) + if self.Pagina is not None: + namespaceprefix_ = self.Pagina_nsprefix_ + ':' if (UseCapturedNS_ and self.Pagina_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sPagina>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Pagina, input_name='Pagina'), namespaceprefix_ , eol_)) + def build(self, node, gds_collector_=None): + self.gds_collector_ = gds_collector_ + if SaveElementTreeNode: + self.gds_elementtree_node_ = node + already_processed = set() + self.ns_prefix_ = node.prefix + self._buildAttributes(node, node.attrib, already_processed) + for child in node: + nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] + self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) + return self + def _buildAttributes(self, node, attrs, already_processed): + pass + def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): + if nodeName_ == 'CPFCNPJTomador': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'CPFCNPJTomador') + value_ = self.gds_validate_string(value_, node, 'CPFCNPJTomador') + self.CPFCNPJTomador = value_ + self.CPFCNPJTomador_nsprefix_ = child_.prefix + elif nodeName_ == 'Competencia': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'Competencia') + value_ = self.gds_validate_string(value_, node, 'Competencia') + self.Competencia = value_ + self.Competencia_nsprefix_ = child_.prefix + elif nodeName_ == 'CPFCNPJPrestador': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'CPFCNPJPrestador') + value_ = self.gds_validate_string(value_, node, 'CPFCNPJPrestador') + self.CPFCNPJPrestador = value_ + self.CPFCNPJPrestador_nsprefix_ = child_.prefix + elif nodeName_ == 'Pagina' and child_.text: + sval_ = child_.text + ival_ = self.gds_parse_integer(sval_, node, 'Pagina') + ival_ = self.gds_validate_integer(ival_, node, 'Pagina') + self.Pagina = ival_ + self.Pagina_nsprefix_ = child_.prefix +# end class NFeRecebidaCompetencia + + +GDSClassesMapping = { +} + + +USAGE_TEXT = """ +Usage: python .py [ -s ] +""" + + +def usage(): + print(USAGE_TEXT) + sys.exit(1) + + +def get_root_tag(node): + tag = Tag_pattern_.match(node.tag).groups()[-1] + prefix_tag = TagNamePrefix + tag + rootClass = GDSClassesMapping.get(prefix_tag) + if rootClass is None: + rootClass = globals().get(prefix_tag) + return tag, rootClass + + +def get_required_ns_prefix_defs(rootNode): + '''Get all name space prefix definitions required in this XML doc. + Return a dictionary of definitions and a char string of definitions. + ''' + nsmap = { + prefix: uri + for node in rootNode.iter() + for (prefix, uri) in node.nsmap.items() + if prefix is not None + } + namespacedefs = ' '.join([ + 'xmlns:{}="{}"'.format(prefix, uri) + for prefix, uri in nsmap.items() + ]) + return nsmap, namespacedefs + + +def parse(inFileName, silence=False, print_warnings=True): + global CapturedNsmap_ + gds_collector = GdsCollector_() + parser = None + doc = parsexml_(inFileName, parser) + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeRecebidaCompetencia' + rootClass = NFeRecebidaCompetencia + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + sys.stdout.write('\n') + rootObj.export( + sys.stdout, 0, name_=rootTag, + namespacedef_=namespacedefs, + pretty_print=True) + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def parseEtree(inFileName, silence=False, print_warnings=True, + mapping=None, reverse_mapping=None, nsmap=None): + parser = None + doc = parsexml_(inFileName, parser) + gds_collector = GdsCollector_() + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeRecebidaCompetencia' + rootClass = NFeRecebidaCompetencia + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + if mapping is None: + mapping = {} + if reverse_mapping is None: + reverse_mapping = {} + rootElement = rootObj.to_etree( + None, name_=rootTag, mapping_=mapping, + reverse_mapping_=reverse_mapping, nsmap_=nsmap) + reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) + # Enable Python to collect the space used by the DOM. + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + content = etree_.tostring( + rootElement, pretty_print=True, + xml_declaration=True, encoding="utf-8") + sys.stdout.write(str(content)) + sys.stdout.write('\n') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj, rootElement, mapping, reverse_node_mapping + + +def parseString(inString, silence=False, print_warnings=True): + '''Parse a string, create the object tree, and export it. + + Arguments: + - inString -- A string. This XML fragment should not start + with an XML declaration containing an encoding. + - silence -- A boolean. If False, export the object. + Returns -- The root object in the tree. + ''' + parser = None + rootNode= parsexmlstring_(inString, parser) + gds_collector = GdsCollector_() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeRecebidaCompetencia' + rootClass = NFeRecebidaCompetencia + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + if not SaveElementTreeNode: + rootNode = None + if not silence: + sys.stdout.write('\n') + rootObj.export( + sys.stdout, 0, name_=rootTag, + namespacedef_='') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def parseLiteral(inFileName, silence=False, print_warnings=True): + parser = None + doc = parsexml_(inFileName, parser) + gds_collector = GdsCollector_() + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeRecebidaCompetencia' + rootClass = NFeRecebidaCompetencia + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + # Enable Python to collect the space used by the DOM. + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + sys.stdout.write('#from ConsultarNFeRecebidaCompetencia import *\n\n') + sys.stdout.write('import ConsultarNFeRecebidaCompetencia as model_\n\n') + sys.stdout.write('rootObj = model_.rootClass(\n') + rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) + sys.stdout.write(')\n') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def main(): + args = sys.argv[1:] + if len(args) == 1: + parse(args[0]) + else: + usage() + + +if __name__ == '__main__': + #import pdb; pdb.set_trace() + main() + +RenameMappings_ = { +} + +# +# Mapping of namespaces to types defined in them +# and the file in which each is defined. +# simpleTypes are marked "ST" and complexTypes "CT". +NamespaceToDefMappings_ = {'http://www.barueri.sp.gov.br/nfe': []} + +__all__ = [ + "NFeRecebidaCompetencia" +] diff --git a/nfselib/barueri/ConsultarNFeRecebidaNumero.py b/nfselib/barueri/ConsultarNFeRecebidaNumero.py new file mode 100644 index 0000000..bb32b78 --- /dev/null +++ b/nfselib/barueri/ConsultarNFeRecebidaNumero.py @@ -0,0 +1,1341 @@ +#TODO + +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# +# Generated Thu Apr 13 03:39:21 2023 by generateDS.py version 2.41.3. +# Python 3.8.10 (default, Mar 13 2023, 10:26:41) [GCC 9.4.0] +# +# Command line options: +# ('-o', 'ConsultarNFeRecebidaNumero.py') +# +# Command line arguments: +# ../../schemas/barueri/ConsultaNFeRecebidaNumero.v1.xsd +# +# Command line: +# /home/andre/.local/bin/generateDS -o "ConsultarNFeRecebidaNumero.py" ../../schemas/barueri/ConsultaNFeRecebidaNumero.v1.xsd +# +# Current working directory (os.getcwd()): +# barueri +# + +import sys +try: + ModulenotfoundExp_ = ModuleNotFoundError +except NameError: + ModulenotfoundExp_ = ImportError +from six.moves import zip_longest +import os +import re as re_ +import base64 +import datetime as datetime_ +import decimal as decimal_ +from lxml import etree as etree_ + + +Validate_simpletypes_ = True +SaveElementTreeNode = True +TagNamePrefix = "" +if sys.version_info.major == 2: + BaseStrType_ = basestring +else: + BaseStrType_ = str + + +def parsexml_(infile, parser=None, **kwargs): + if parser is None: + # Use the lxml ElementTree compatible parser so that, e.g., + # we ignore comments. + try: + parser = etree_.ETCompatXMLParser() + except AttributeError: + # fallback to xml.etree + parser = etree_.XMLParser() + try: + if isinstance(infile, os.PathLike): + infile = os.path.join(infile) + except AttributeError: + pass + doc = etree_.parse(infile, parser=parser, **kwargs) + return doc + +def parsexmlstring_(instring, parser=None, **kwargs): + if parser is None: + # Use the lxml ElementTree compatible parser so that, e.g., + # we ignore comments. + try: + parser = etree_.ETCompatXMLParser() + except AttributeError: + # fallback to xml.etree + parser = etree_.XMLParser() + element = etree_.fromstring(instring, parser=parser, **kwargs) + return element + +# +# Namespace prefix definition table (and other attributes, too) +# +# The module generatedsnamespaces, if it is importable, must contain +# a dictionary named GeneratedsNamespaceDefs. This Python dictionary +# should map element type names (strings) to XML schema namespace prefix +# definitions. The export method for any class for which there is +# a namespace prefix definition, will export that definition in the +# XML representation of that element. See the export method of +# any generated element type class for an example of the use of this +# table. +# A sample table is: +# +# # File: generatedsnamespaces.py +# +# GenerateDSNamespaceDefs = { +# "ElementtypeA": "http://www.xxx.com/namespaceA", +# "ElementtypeB": "http://www.xxx.com/namespaceB", +# } +# +# Additionally, the generatedsnamespaces module can contain a python +# dictionary named GenerateDSNamespaceTypePrefixes that associates element +# types with the namespace prefixes that are to be added to the +# "xsi:type" attribute value. See the _exportAttributes method of +# any generated element type and the generation of "xsi:type" for an +# example of the use of this table. +# An example table: +# +# # File: generatedsnamespaces.py +# +# GenerateDSNamespaceTypePrefixes = { +# "ElementtypeC": "aaa:", +# "ElementtypeD": "bbb:", +# } +# + +try: + from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ +except ModulenotfoundExp_ : + GenerateDSNamespaceDefs_ = {} +try: + from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ +except ModulenotfoundExp_ : + GenerateDSNamespaceTypePrefixes_ = {} + +# +# You can replace the following class definition by defining an +# importable module named "generatedscollector" containing a class +# named "GdsCollector". See the default class definition below for +# clues about the possible content of that class. +# +try: + from generatedscollector import GdsCollector as GdsCollector_ +except ModulenotfoundExp_ : + + class GdsCollector_(object): + + def __init__(self, messages=None): + if messages is None: + self.messages = [] + else: + self.messages = messages + + def add_message(self, msg): + self.messages.append(msg) + + def get_messages(self): + return self.messages + + def clear_messages(self): + self.messages = [] + + def print_messages(self): + for msg in self.messages: + print("Warning: {}".format(msg)) + + def write_messages(self, outstream): + for msg in self.messages: + outstream.write("Warning: {}\n".format(msg)) + + +# +# The super-class for enum types +# + +try: + from enum import Enum +except ModulenotfoundExp_ : + Enum = object + +# +# The root super-class for element type classes +# +# Calls to the methods in these classes are generated by generateDS.py. +# You can replace these methods by re-implementing the following class +# in a module named generatedssuper.py. + +try: + from generatedssuper import GeneratedsSuper +except ModulenotfoundExp_ as exp: + try: + from generatedssupersuper import GeneratedsSuperSuper + except ModulenotfoundExp_ as exp: + class GeneratedsSuperSuper(object): + pass + + class GeneratedsSuper(GeneratedsSuperSuper): + __hash__ = object.__hash__ + tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') + class _FixedOffsetTZ(datetime_.tzinfo): + def __init__(self, offset, name): + self.__offset = datetime_.timedelta(minutes=offset) + self.__name = name + def utcoffset(self, dt): + return self.__offset + def tzname(self, dt): + return self.__name + def dst(self, dt): + return None + def __str__(self): + settings = { + 'str_pretty_print': True, + 'str_indent_level': 0, + 'str_namespaceprefix': '', + 'str_name': self.__class__.__name__, + 'str_namespacedefs': '', + } + for n in settings: + if hasattr(self, n): + settings[n] = getattr(self, n) + if sys.version_info.major == 2: + from StringIO import StringIO + else: + from io import StringIO + output = StringIO() + self.export( + output, + settings['str_indent_level'], + pretty_print=settings['str_pretty_print'], + namespaceprefix_=settings['str_namespaceprefix'], + name_=settings['str_name'], + namespacedef_=settings['str_namespacedefs'] + ) + strval = output.getvalue() + output.close() + return strval + def gds_format_string(self, input_data, input_name=''): + return input_data + def gds_parse_string(self, input_data, node=None, input_name=''): + return input_data + def gds_validate_string(self, input_data, node=None, input_name=''): + if not input_data: + return '' + else: + return input_data + def gds_format_base64(self, input_data, input_name=''): + return base64.b64encode(input_data).decode('ascii') + def gds_validate_base64(self, input_data, node=None, input_name=''): + return input_data + def gds_format_integer(self, input_data, input_name=''): + return '%d' % int(input_data) + def gds_parse_integer(self, input_data, node=None, input_name=''): + try: + ival = int(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires integer value: %s' % exp) + return ival + def gds_validate_integer(self, input_data, node=None, input_name=''): + try: + value = int(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires integer value') + return value + def gds_format_integer_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_integer_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + int(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of integer values') + return values + def gds_format_float(self, input_data, input_name=''): + return ('%.15f' % float(input_data)).rstrip('0') + def gds_parse_float(self, input_data, node=None, input_name=''): + try: + fval_ = float(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires float or double value: %s' % exp) + return fval_ + def gds_validate_float(self, input_data, node=None, input_name=''): + try: + value = float(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires float value') + return value + def gds_format_float_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_float_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + float(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of float values') + return values + def gds_format_decimal(self, input_data, input_name=''): + return_value = '%s' % input_data + if '.' in return_value: + return_value = return_value.rstrip('0') + if return_value.endswith('.'): + return_value = return_value.rstrip('.') + return return_value + def gds_parse_decimal(self, input_data, node=None, input_name=''): + try: + decimal_value = decimal_.Decimal(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires decimal value') + return decimal_value + def gds_validate_decimal(self, input_data, node=None, input_name=''): + try: + value = decimal_.Decimal(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires decimal value') + return value + def gds_format_decimal_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return ' '.join([self.gds_format_decimal(item) for item in input_data]) + def gds_validate_decimal_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + decimal_.Decimal(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of decimal values') + return values + def gds_format_double(self, input_data, input_name=''): + return '%s' % input_data + def gds_parse_double(self, input_data, node=None, input_name=''): + try: + fval_ = float(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires double or float value: %s' % exp) + return fval_ + def gds_validate_double(self, input_data, node=None, input_name=''): + try: + value = float(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires double or float value') + return value + def gds_format_double_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_double_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + float(value) + except (TypeError, ValueError): + raise_parse_error( + node, 'Requires sequence of double or float values') + return values + def gds_format_boolean(self, input_data, input_name=''): + return ('%s' % input_data).lower() + def gds_parse_boolean(self, input_data, node=None, input_name=''): + input_data = input_data.strip() + if input_data in ('true', '1'): + bval = True + elif input_data in ('false', '0'): + bval = False + else: + raise_parse_error(node, 'Requires boolean value') + return bval + def gds_validate_boolean(self, input_data, node=None, input_name=''): + if input_data not in (True, 1, False, 0, ): + raise_parse_error( + node, + 'Requires boolean value ' + '(one of True, 1, False, 0)') + return input_data + def gds_format_boolean_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_boolean_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + value = self.gds_parse_boolean(value, node, input_name) + if value not in (True, 1, False, 0, ): + raise_parse_error( + node, + 'Requires sequence of boolean values ' + '(one of True, 1, False, 0)') + return values + def gds_validate_datetime(self, input_data, node=None, input_name=''): + return input_data + def gds_format_datetime(self, input_data, input_name=''): + if input_data.microsecond == 0: + _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( + input_data.year, + input_data.month, + input_data.day, + input_data.hour, + input_data.minute, + input_data.second, + ) + else: + _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( + input_data.year, + input_data.month, + input_data.day, + input_data.hour, + input_data.minute, + input_data.second, + ('%f' % (float(input_data.microsecond) / 1000000))[2:], + ) + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) + return _svalue + @classmethod + def gds_parse_datetime(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + time_parts = input_data.split('.') + if len(time_parts) > 1: + micro_seconds = int(float('0.' + time_parts[1]) * 1000000) + input_data = '%s.%s' % ( + time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) + dt = datetime_.datetime.strptime( + input_data, '%Y-%m-%dT%H:%M:%S.%f') + else: + dt = datetime_.datetime.strptime( + input_data, '%Y-%m-%dT%H:%M:%S') + dt = dt.replace(tzinfo=tz) + return dt + def gds_validate_date(self, input_data, node=None, input_name=''): + return input_data + def gds_format_date(self, input_data, input_name=''): + _svalue = '%04d-%02d-%02d' % ( + input_data.year, + input_data.month, + input_data.day, + ) + try: + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format( + hours, minutes) + except AttributeError: + pass + return _svalue + @classmethod + def gds_parse_date(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') + dt = dt.replace(tzinfo=tz) + return dt.date() + def gds_validate_time(self, input_data, node=None, input_name=''): + return input_data + def gds_format_time(self, input_data, input_name=''): + if input_data.microsecond == 0: + _svalue = '%02d:%02d:%02d' % ( + input_data.hour, + input_data.minute, + input_data.second, + ) + else: + _svalue = '%02d:%02d:%02d.%s' % ( + input_data.hour, + input_data.minute, + input_data.second, + ('%f' % (float(input_data.microsecond) / 1000000))[2:], + ) + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) + return _svalue + def gds_validate_simple_patterns(self, patterns, target): + # pat is a list of lists of strings/patterns. + # The target value must match at least one of the patterns + # in order for the test to succeed. + found1 = True + target = str(target) + for patterns1 in patterns: + found2 = False + for patterns2 in patterns1: + mo = re_.search(patterns2, target) + if mo is not None and len(mo.group(0)) == len(target): + found2 = True + break + if not found2: + found1 = False + break + return found1 + @classmethod + def gds_parse_time(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + if len(input_data.split('.')) > 1: + dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') + else: + dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') + dt = dt.replace(tzinfo=tz) + return dt.time() + def gds_check_cardinality_( + self, value, input_name, + min_occurs=0, max_occurs=1, required=None): + if value is None: + length = 0 + elif isinstance(value, list): + length = len(value) + else: + length = 1 + if required is not None : + if required and length < 1: + self.gds_collector_.add_message( + "Required value {}{} is missing".format( + input_name, self.gds_get_node_lineno_())) + if length < min_occurs: + self.gds_collector_.add_message( + "Number of values for {}{} is below " + "the minimum allowed, " + "expected at least {}, found {}".format( + input_name, self.gds_get_node_lineno_(), + min_occurs, length)) + elif length > max_occurs: + self.gds_collector_.add_message( + "Number of values for {}{} is above " + "the maximum allowed, " + "expected at most {}, found {}".format( + input_name, self.gds_get_node_lineno_(), + max_occurs, length)) + def gds_validate_builtin_ST_( + self, validator, value, input_name, + min_occurs=None, max_occurs=None, required=None): + if value is not None: + try: + validator(value, input_name=input_name) + except GDSParseError as parse_error: + self.gds_collector_.add_message(str(parse_error)) + def gds_validate_defined_ST_( + self, validator, value, input_name, + min_occurs=None, max_occurs=None, required=None): + if value is not None: + try: + validator(value) + except GDSParseError as parse_error: + self.gds_collector_.add_message(str(parse_error)) + def gds_str_lower(self, instring): + return instring.lower() + def get_path_(self, node): + path_list = [] + self.get_path_list_(node, path_list) + path_list.reverse() + path = '/'.join(path_list) + return path + Tag_strip_pattern_ = re_.compile(r'\{.*\}') + def get_path_list_(self, node, path_list): + if node is None: + return + tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) + if tag: + path_list.append(tag) + self.get_path_list_(node.getparent(), path_list) + def get_class_obj_(self, node, default_class=None): + class_obj1 = default_class + if 'xsi' in node.nsmap: + classname = node.get('{%s}type' % node.nsmap['xsi']) + if classname is not None: + names = classname.split(':') + if len(names) == 2: + classname = names[1] + class_obj2 = globals().get(classname) + if class_obj2 is not None: + class_obj1 = class_obj2 + return class_obj1 + def gds_build_any(self, node, type_name=None): + # provide default value in case option --disable-xml is used. + content = "" + content = etree_.tostring(node, encoding="unicode") + return content + @classmethod + def gds_reverse_node_mapping(cls, mapping): + return dict(((v, k) for k, v in mapping.items())) + @staticmethod + def gds_encode(instring): + if sys.version_info.major == 2: + if ExternalEncoding: + encoding = ExternalEncoding + else: + encoding = 'utf-8' + return instring.encode(encoding) + else: + return instring + @staticmethod + def convert_unicode(instring): + if isinstance(instring, str): + result = quote_xml(instring) + elif sys.version_info.major == 2 and isinstance(instring, unicode): + result = quote_xml(instring).encode('utf8') + else: + result = GeneratedsSuper.gds_encode(str(instring)) + return result + def __eq__(self, other): + def excl_select_objs_(obj): + return (obj[0] != 'parent_object_' and + obj[0] != 'gds_collector_') + if type(self) != type(other): + return False + return all(x == y for x, y in zip_longest( + filter(excl_select_objs_, self.__dict__.items()), + filter(excl_select_objs_, other.__dict__.items()))) + def __ne__(self, other): + return not self.__eq__(other) + # Django ETL transform hooks. + def gds_djo_etl_transform(self): + pass + def gds_djo_etl_transform_db_obj(self, dbobj): + pass + # SQLAlchemy ETL transform hooks. + def gds_sqa_etl_transform(self): + return 0, None + def gds_sqa_etl_transform_db_obj(self, dbobj): + pass + def gds_get_node_lineno_(self): + if (hasattr(self, "gds_elementtree_node_") and + self.gds_elementtree_node_ is not None): + return ' near line {}'.format( + self.gds_elementtree_node_.sourceline) + else: + return "" + + + def getSubclassFromModule_(module, class_): + '''Get the subclass of a class from a specific module.''' + name = class_.__name__ + 'Sub' + if hasattr(module, name): + return getattr(module, name) + else: + return None + + +# +# If you have installed IPython you can uncomment and use the following. +# IPython is available from http://ipython.scipy.org/. +# + +## from IPython.Shell import IPShellEmbed +## args = '' +## ipshell = IPShellEmbed(args, +## banner = 'Dropping into IPython', +## exit_msg = 'Leaving Interpreter, back to program.') + +# Then use the following line where and when you want to drop into the +# IPython shell: +# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') + +# +# Globals +# + +ExternalEncoding = '' +# Set this to false in order to deactivate during export, the use of +# name space prefixes captured from the input document. +UseCapturedNS_ = True +CapturedNsmap_ = {} +Tag_pattern_ = re_.compile(r'({.*})?(.*)') +String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") +Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') +CDATA_pattern_ = re_.compile(r"", re_.DOTALL) + +# Change this to redirect the generated superclass module to use a +# specific subclass module. +CurrentSubclassModule_ = None + +# +# Support/utility functions. +# + + +def showIndent(outfile, level, pretty_print=True): + if pretty_print: + for idx in range(level): + outfile.write(' ') + + +def quote_xml(inStr): + "Escape markup chars, but do not modify CDATA sections." + if not inStr: + return '' + s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) + s2 = '' + pos = 0 + matchobjects = CDATA_pattern_.finditer(s1) + for mo in matchobjects: + s3 = s1[pos:mo.start()] + s2 += quote_xml_aux(s3) + s2 += s1[mo.start():mo.end()] + pos = mo.end() + s3 = s1[pos:] + s2 += quote_xml_aux(s3) + return s2 + + +def quote_xml_aux(inStr): + s1 = inStr.replace('&', '&') + s1 = s1.replace('<', '<') + s1 = s1.replace('>', '>') + return s1 + + +def quote_attrib(inStr): + s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) + s1 = s1.replace('&', '&') + s1 = s1.replace('<', '<') + s1 = s1.replace('>', '>') + s1 = s1.replace('\n', ' ') + if '"' in s1: + if "'" in s1: + s1 = '"%s"' % s1.replace('"', """) + else: + s1 = "'%s'" % s1 + else: + s1 = '"%s"' % s1 + return s1 + + +def quote_python(inStr): + s1 = inStr + if s1.find("'") == -1: + if s1.find('\n') == -1: + return "'%s'" % s1 + else: + return "'''%s'''" % s1 + else: + if s1.find('"') != -1: + s1 = s1.replace('"', '\\"') + if s1.find('\n') == -1: + return '"%s"' % s1 + else: + return '"""%s"""' % s1 + + +def get_all_text_(node): + if node.text is not None: + text = node.text + else: + text = '' + for child in node: + if child.tail is not None: + text += child.tail + return text + + +def find_attr_value_(attr_name, node): + attrs = node.attrib + attr_parts = attr_name.split(':') + value = None + if len(attr_parts) == 1: + value = attrs.get(attr_name) + elif len(attr_parts) == 2: + prefix, name = attr_parts + if prefix == 'xml': + namespace = 'http://www.w3.org/XML/1998/namespace' + else: + namespace = node.nsmap.get(prefix) + if namespace is not None: + value = attrs.get('{%s}%s' % (namespace, name, )) + return value + + +def encode_str_2_3(instr): + return instr + + +class GDSParseError(Exception): + pass + + +def raise_parse_error(node, msg): + if node is not None: + msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) + raise GDSParseError(msg) + + +class MixedContainer: + # Constants for category: + CategoryNone = 0 + CategoryText = 1 + CategorySimple = 2 + CategoryComplex = 3 + # Constants for content_type: + TypeNone = 0 + TypeText = 1 + TypeString = 2 + TypeInteger = 3 + TypeFloat = 4 + TypeDecimal = 5 + TypeDouble = 6 + TypeBoolean = 7 + TypeBase64 = 8 + def __init__(self, category, content_type, name, value): + self.category = category + self.content_type = content_type + self.name = name + self.value = value + def getCategory(self): + return self.category + def getContenttype(self, content_type): + return self.content_type + def getValue(self): + return self.value + def getName(self): + return self.name + def export(self, outfile, level, name, namespace, + pretty_print=True): + if self.category == MixedContainer.CategoryText: + # Prevent exporting empty content as empty lines. + if self.value.strip(): + outfile.write(self.value) + elif self.category == MixedContainer.CategorySimple: + self.exportSimple(outfile, level, name) + else: # category == MixedContainer.CategoryComplex + self.value.export( + outfile, level, namespace, name_=name, + pretty_print=pretty_print) + def exportSimple(self, outfile, level, name): + if self.content_type == MixedContainer.TypeString: + outfile.write('<%s>%s' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeInteger or \ + self.content_type == MixedContainer.TypeBoolean: + outfile.write('<%s>%d' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeFloat or \ + self.content_type == MixedContainer.TypeDecimal: + outfile.write('<%s>%f' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeDouble: + outfile.write('<%s>%g' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeBase64: + outfile.write('<%s>%s' % ( + self.name, + base64.b64encode(self.value), + self.name)) + def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): + if self.category == MixedContainer.CategoryText: + # Prevent exporting empty content as empty lines. + if self.value.strip(): + if len(element) > 0: + if element[-1].tail is None: + element[-1].tail = self.value + else: + element[-1].tail += self.value + else: + if element.text is None: + element.text = self.value + else: + element.text += self.value + elif self.category == MixedContainer.CategorySimple: + subelement = etree_.SubElement( + element, '%s' % self.name) + subelement.text = self.to_etree_simple() + else: # category == MixedContainer.CategoryComplex + self.value.to_etree(element) + def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): + if self.content_type == MixedContainer.TypeString: + text = self.value + elif (self.content_type == MixedContainer.TypeInteger or + self.content_type == MixedContainer.TypeBoolean): + text = '%d' % self.value + elif (self.content_type == MixedContainer.TypeFloat or + self.content_type == MixedContainer.TypeDecimal): + text = '%f' % self.value + elif self.content_type == MixedContainer.TypeDouble: + text = '%g' % self.value + elif self.content_type == MixedContainer.TypeBase64: + text = '%s' % base64.b64encode(self.value) + return text + def exportLiteral(self, outfile, level, name): + if self.category == MixedContainer.CategoryText: + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( + self.category, self.content_type, + self.name, self.value)) + elif self.category == MixedContainer.CategorySimple: + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( + self.category, self.content_type, + self.name, self.value)) + else: # category == MixedContainer.CategoryComplex + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s",\n' % ( + self.category, self.content_type, self.name,)) + self.value.exportLiteral(outfile, level + 1) + showIndent(outfile, level) + outfile.write(')\n') + + +class MemberSpec_(object): + def __init__(self, name='', data_type='', container=0, + optional=0, child_attrs=None, choice=None): + self.name = name + self.data_type = data_type + self.container = container + self.child_attrs = child_attrs + self.choice = choice + self.optional = optional + def set_name(self, name): self.name = name + def get_name(self): return self.name + def set_data_type(self, data_type): self.data_type = data_type + def get_data_type_chain(self): return self.data_type + def get_data_type(self): + if isinstance(self.data_type, list): + if len(self.data_type) > 0: + return self.data_type[-1] + else: + return 'xs:string' + else: + return self.data_type + def set_container(self, container): self.container = container + def get_container(self): return self.container + def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs + def get_child_attrs(self): return self.child_attrs + def set_choice(self, choice): self.choice = choice + def get_choice(self): return self.choice + def set_optional(self, optional): self.optional = optional + def get_optional(self): return self.optional + + +def _cast(typ, value): + if typ is None or value is None: + return value + return typ(value) + +# +# Data representation classes. +# + + +class NFeRecebidaNumero(GeneratedsSuper): + """CPFCNPJPrestador -- CNPJ/CPF do Prestador do Servi + ç + o, ou seja, aquele que emitiu a nota ao Tomador + NumeroNota -- Numero da nota foi emitida para o tomador. + + """ + __hash__ = GeneratedsSuper.__hash__ + subclass = None + superclass = None + def __init__(self, CPFCNPJTomador=None, CPFCNPJPrestador=None, NumeroNota=None, gds_collector_=None, **kwargs_): + self.gds_collector_ = gds_collector_ + self.gds_elementtree_node_ = None + self.original_tagname_ = None + self.parent_object_ = kwargs_.get('parent_object_') + self.ns_prefix_ = None + self.CPFCNPJTomador = CPFCNPJTomador + self.CPFCNPJTomador_nsprefix_ = None + self.CPFCNPJPrestador = CPFCNPJPrestador + self.CPFCNPJPrestador_nsprefix_ = None + self.NumeroNota = NumeroNota + self.NumeroNota_nsprefix_ = None + def factory(*args_, **kwargs_): + if CurrentSubclassModule_ is not None: + subclass = getSubclassFromModule_( + CurrentSubclassModule_, NFeRecebidaNumero) + if subclass is not None: + return subclass(*args_, **kwargs_) + if NFeRecebidaNumero.subclass: + return NFeRecebidaNumero.subclass(*args_, **kwargs_) + else: + return NFeRecebidaNumero(*args_, **kwargs_) + factory = staticmethod(factory) + def get_ns_prefix_(self): + return self.ns_prefix_ + def set_ns_prefix_(self, ns_prefix): + self.ns_prefix_ = ns_prefix + def get_CPFCNPJTomador(self): + return self.CPFCNPJTomador + def set_CPFCNPJTomador(self, CPFCNPJTomador): + self.CPFCNPJTomador = CPFCNPJTomador + def get_CPFCNPJPrestador(self): + return self.CPFCNPJPrestador + def set_CPFCNPJPrestador(self, CPFCNPJPrestador): + self.CPFCNPJPrestador = CPFCNPJPrestador + def get_NumeroNota(self): + return self.NumeroNota + def set_NumeroNota(self, NumeroNota): + self.NumeroNota = NumeroNota + def _hasContent(self): + if ( + self.CPFCNPJTomador is not None or + self.CPFCNPJPrestador is not None or + self.NumeroNota is not None + ): + return True + else: + return False + def export(self, outfile, level, namespaceprefix_='', namespacedef_=' xmlns:None="http://www.barueri.sp.gov.br/nfe" ', name_='NFeRecebidaNumero', pretty_print=True): + imported_ns_def_ = GenerateDSNamespaceDefs_.get('NFeRecebidaNumero') + if imported_ns_def_ is not None: + namespacedef_ = imported_ns_def_ + if pretty_print: + eol_ = '\n' + else: + eol_ = '' + if self.original_tagname_ is not None and name_ == 'NFeRecebidaNumero': + name_ = self.original_tagname_ + if UseCapturedNS_ and self.ns_prefix_: + namespaceprefix_ = self.ns_prefix_ + ':' + showIndent(outfile, level, pretty_print) + outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) + already_processed = set() + self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='NFeRecebidaNumero') + if self._hasContent(): + outfile.write('>%s' % (eol_, )) + self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='NFeRecebidaNumero', pretty_print=pretty_print) + showIndent(outfile, level, pretty_print) + outfile.write('%s' % (namespaceprefix_, name_, eol_)) + else: + outfile.write('/>%s' % (eol_, )) + def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='NFeRecebidaNumero'): + pass + def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_=' xmlns:None="http://www.barueri.sp.gov.br/nfe" ', name_='NFeRecebidaNumero', fromsubclass_=False, pretty_print=True): + if pretty_print: + eol_ = '\n' + else: + eol_ = '' + if self.CPFCNPJTomador is not None: + namespaceprefix_ = self.CPFCNPJTomador_nsprefix_ + ':' if (UseCapturedNS_ and self.CPFCNPJTomador_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sCPFCNPJTomador>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CPFCNPJTomador), input_name='CPFCNPJTomador')), namespaceprefix_ , eol_)) + if self.CPFCNPJPrestador is not None: + namespaceprefix_ = self.CPFCNPJPrestador_nsprefix_ + ':' if (UseCapturedNS_ and self.CPFCNPJPrestador_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sCPFCNPJPrestador>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CPFCNPJPrestador), input_name='CPFCNPJPrestador')), namespaceprefix_ , eol_)) + if self.NumeroNota is not None: + namespaceprefix_ = self.NumeroNota_nsprefix_ + ':' if (UseCapturedNS_ and self.NumeroNota_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sNumeroNota>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.NumeroNota, input_name='NumeroNota'), namespaceprefix_ , eol_)) + def build(self, node, gds_collector_=None): + self.gds_collector_ = gds_collector_ + if SaveElementTreeNode: + self.gds_elementtree_node_ = node + already_processed = set() + self.ns_prefix_ = node.prefix + self._buildAttributes(node, node.attrib, already_processed) + for child in node: + nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] + self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) + return self + def _buildAttributes(self, node, attrs, already_processed): + pass + def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): + if nodeName_ == 'CPFCNPJTomador': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'CPFCNPJTomador') + value_ = self.gds_validate_string(value_, node, 'CPFCNPJTomador') + self.CPFCNPJTomador = value_ + self.CPFCNPJTomador_nsprefix_ = child_.prefix + elif nodeName_ == 'CPFCNPJPrestador': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'CPFCNPJPrestador') + value_ = self.gds_validate_string(value_, node, 'CPFCNPJPrestador') + self.CPFCNPJPrestador = value_ + self.CPFCNPJPrestador_nsprefix_ = child_.prefix + elif nodeName_ == 'NumeroNota' and child_.text: + sval_ = child_.text + ival_ = self.gds_parse_integer(sval_, node, 'NumeroNota') + ival_ = self.gds_validate_integer(ival_, node, 'NumeroNota') + self.NumeroNota = ival_ + self.NumeroNota_nsprefix_ = child_.prefix +# end class NFeRecebidaNumero + + +GDSClassesMapping = { +} + + +USAGE_TEXT = """ +Usage: python .py [ -s ] +""" + + +def usage(): + print(USAGE_TEXT) + sys.exit(1) + + +def get_root_tag(node): + tag = Tag_pattern_.match(node.tag).groups()[-1] + prefix_tag = TagNamePrefix + tag + rootClass = GDSClassesMapping.get(prefix_tag) + if rootClass is None: + rootClass = globals().get(prefix_tag) + return tag, rootClass + + +def get_required_ns_prefix_defs(rootNode): + '''Get all name space prefix definitions required in this XML doc. + Return a dictionary of definitions and a char string of definitions. + ''' + nsmap = { + prefix: uri + for node in rootNode.iter() + for (prefix, uri) in node.nsmap.items() + if prefix is not None + } + namespacedefs = ' '.join([ + 'xmlns:{}="{}"'.format(prefix, uri) + for prefix, uri in nsmap.items() + ]) + return nsmap, namespacedefs + + +def parse(inFileName, silence=False, print_warnings=True): + global CapturedNsmap_ + gds_collector = GdsCollector_() + parser = None + doc = parsexml_(inFileName, parser) + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeRecebidaNumero' + rootClass = NFeRecebidaNumero + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + sys.stdout.write('\n') + rootObj.export( + sys.stdout, 0, name_=rootTag, + namespacedef_=namespacedefs, + pretty_print=True) + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def parseEtree(inFileName, silence=False, print_warnings=True, + mapping=None, reverse_mapping=None, nsmap=None): + parser = None + doc = parsexml_(inFileName, parser) + gds_collector = GdsCollector_() + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeRecebidaNumero' + rootClass = NFeRecebidaNumero + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + if mapping is None: + mapping = {} + if reverse_mapping is None: + reverse_mapping = {} + rootElement = rootObj.to_etree( + None, name_=rootTag, mapping_=mapping, + reverse_mapping_=reverse_mapping, nsmap_=nsmap) + reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) + # Enable Python to collect the space used by the DOM. + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + content = etree_.tostring( + rootElement, pretty_print=True, + xml_declaration=True, encoding="utf-8") + sys.stdout.write(str(content)) + sys.stdout.write('\n') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj, rootElement, mapping, reverse_node_mapping + + +def parseString(inString, silence=False, print_warnings=True): + '''Parse a string, create the object tree, and export it. + + Arguments: + - inString -- A string. This XML fragment should not start + with an XML declaration containing an encoding. + - silence -- A boolean. If False, export the object. + Returns -- The root object in the tree. + ''' + parser = None + rootNode= parsexmlstring_(inString, parser) + gds_collector = GdsCollector_() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeRecebidaNumero' + rootClass = NFeRecebidaNumero + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + if not SaveElementTreeNode: + rootNode = None + if not silence: + sys.stdout.write('\n') + rootObj.export( + sys.stdout, 0, name_=rootTag, + namespacedef_='') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def parseLiteral(inFileName, silence=False, print_warnings=True): + parser = None + doc = parsexml_(inFileName, parser) + gds_collector = GdsCollector_() + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeRecebidaNumero' + rootClass = NFeRecebidaNumero + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + # Enable Python to collect the space used by the DOM. + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + sys.stdout.write('#from ConsultarNFeRecebidaNumero import *\n\n') + sys.stdout.write('import ConsultarNFeRecebidaNumero as model_\n\n') + sys.stdout.write('rootObj = model_.rootClass(\n') + rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) + sys.stdout.write(')\n') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def main(): + args = sys.argv[1:] + if len(args) == 1: + parse(args[0]) + else: + usage() + + +if __name__ == '__main__': + #import pdb; pdb.set_trace() + main() + +RenameMappings_ = { +} + +# +# Mapping of namespaces to types defined in them +# and the file in which each is defined. +# simpleTypes are marked "ST" and complexTypes "CT". +NamespaceToDefMappings_ = {'http://www.barueri.sp.gov.br/nfe': []} + +__all__ = [ + "NFeRecebidaNumero" +] diff --git a/nfselib/barueri/ConsultarNFeRecebidaPeriodo.py b/nfselib/barueri/ConsultarNFeRecebidaPeriodo.py new file mode 100644 index 0000000..fa06b36 --- /dev/null +++ b/nfselib/barueri/ConsultarNFeRecebidaPeriodo.py @@ -0,0 +1,1391 @@ +#TODO + +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# +# Generated Thu Apr 13 03:39:38 2023 by generateDS.py version 2.41.3. +# Python 3.8.10 (default, Mar 13 2023, 10:26:41) [GCC 9.4.0] +# +# Command line options: +# ('-o', 'ConsultarNFeRecebidaPeriodo.py') +# +# Command line arguments: +# ../../schemas/barueri/ConsultaNFeRecebidaPeriodo.v1.xsd +# +# Command line: +# /home/andre/.local/bin/generateDS -o "ConsultarNFeRecebidaPeriodo.py" ../../schemas/barueri/ConsultaNFeRecebidaPeriodo.v1.xsd +# +# Current working directory (os.getcwd()): +# barueri +# + +import sys +try: + ModulenotfoundExp_ = ModuleNotFoundError +except NameError: + ModulenotfoundExp_ = ImportError +from six.moves import zip_longest +import os +import re as re_ +import base64 +import datetime as datetime_ +import decimal as decimal_ +from lxml import etree as etree_ + + +Validate_simpletypes_ = True +SaveElementTreeNode = True +TagNamePrefix = "" +if sys.version_info.major == 2: + BaseStrType_ = basestring +else: + BaseStrType_ = str + + +def parsexml_(infile, parser=None, **kwargs): + if parser is None: + # Use the lxml ElementTree compatible parser so that, e.g., + # we ignore comments. + try: + parser = etree_.ETCompatXMLParser() + except AttributeError: + # fallback to xml.etree + parser = etree_.XMLParser() + try: + if isinstance(infile, os.PathLike): + infile = os.path.join(infile) + except AttributeError: + pass + doc = etree_.parse(infile, parser=parser, **kwargs) + return doc + +def parsexmlstring_(instring, parser=None, **kwargs): + if parser is None: + # Use the lxml ElementTree compatible parser so that, e.g., + # we ignore comments. + try: + parser = etree_.ETCompatXMLParser() + except AttributeError: + # fallback to xml.etree + parser = etree_.XMLParser() + element = etree_.fromstring(instring, parser=parser, **kwargs) + return element + +# +# Namespace prefix definition table (and other attributes, too) +# +# The module generatedsnamespaces, if it is importable, must contain +# a dictionary named GeneratedsNamespaceDefs. This Python dictionary +# should map element type names (strings) to XML schema namespace prefix +# definitions. The export method for any class for which there is +# a namespace prefix definition, will export that definition in the +# XML representation of that element. See the export method of +# any generated element type class for an example of the use of this +# table. +# A sample table is: +# +# # File: generatedsnamespaces.py +# +# GenerateDSNamespaceDefs = { +# "ElementtypeA": "http://www.xxx.com/namespaceA", +# "ElementtypeB": "http://www.xxx.com/namespaceB", +# } +# +# Additionally, the generatedsnamespaces module can contain a python +# dictionary named GenerateDSNamespaceTypePrefixes that associates element +# types with the namespace prefixes that are to be added to the +# "xsi:type" attribute value. See the _exportAttributes method of +# any generated element type and the generation of "xsi:type" for an +# example of the use of this table. +# An example table: +# +# # File: generatedsnamespaces.py +# +# GenerateDSNamespaceTypePrefixes = { +# "ElementtypeC": "aaa:", +# "ElementtypeD": "bbb:", +# } +# + +try: + from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ +except ModulenotfoundExp_ : + GenerateDSNamespaceDefs_ = {} +try: + from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ +except ModulenotfoundExp_ : + GenerateDSNamespaceTypePrefixes_ = {} + +# +# You can replace the following class definition by defining an +# importable module named "generatedscollector" containing a class +# named "GdsCollector". See the default class definition below for +# clues about the possible content of that class. +# +try: + from generatedscollector import GdsCollector as GdsCollector_ +except ModulenotfoundExp_ : + + class GdsCollector_(object): + + def __init__(self, messages=None): + if messages is None: + self.messages = [] + else: + self.messages = messages + + def add_message(self, msg): + self.messages.append(msg) + + def get_messages(self): + return self.messages + + def clear_messages(self): + self.messages = [] + + def print_messages(self): + for msg in self.messages: + print("Warning: {}".format(msg)) + + def write_messages(self, outstream): + for msg in self.messages: + outstream.write("Warning: {}\n".format(msg)) + + +# +# The super-class for enum types +# + +try: + from enum import Enum +except ModulenotfoundExp_ : + Enum = object + +# +# The root super-class for element type classes +# +# Calls to the methods in these classes are generated by generateDS.py. +# You can replace these methods by re-implementing the following class +# in a module named generatedssuper.py. + +try: + from generatedssuper import GeneratedsSuper +except ModulenotfoundExp_ as exp: + try: + from generatedssupersuper import GeneratedsSuperSuper + except ModulenotfoundExp_ as exp: + class GeneratedsSuperSuper(object): + pass + + class GeneratedsSuper(GeneratedsSuperSuper): + __hash__ = object.__hash__ + tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') + class _FixedOffsetTZ(datetime_.tzinfo): + def __init__(self, offset, name): + self.__offset = datetime_.timedelta(minutes=offset) + self.__name = name + def utcoffset(self, dt): + return self.__offset + def tzname(self, dt): + return self.__name + def dst(self, dt): + return None + def __str__(self): + settings = { + 'str_pretty_print': True, + 'str_indent_level': 0, + 'str_namespaceprefix': '', + 'str_name': self.__class__.__name__, + 'str_namespacedefs': '', + } + for n in settings: + if hasattr(self, n): + settings[n] = getattr(self, n) + if sys.version_info.major == 2: + from StringIO import StringIO + else: + from io import StringIO + output = StringIO() + self.export( + output, + settings['str_indent_level'], + pretty_print=settings['str_pretty_print'], + namespaceprefix_=settings['str_namespaceprefix'], + name_=settings['str_name'], + namespacedef_=settings['str_namespacedefs'] + ) + strval = output.getvalue() + output.close() + return strval + def gds_format_string(self, input_data, input_name=''): + return input_data + def gds_parse_string(self, input_data, node=None, input_name=''): + return input_data + def gds_validate_string(self, input_data, node=None, input_name=''): + if not input_data: + return '' + else: + return input_data + def gds_format_base64(self, input_data, input_name=''): + return base64.b64encode(input_data).decode('ascii') + def gds_validate_base64(self, input_data, node=None, input_name=''): + return input_data + def gds_format_integer(self, input_data, input_name=''): + return '%d' % int(input_data) + def gds_parse_integer(self, input_data, node=None, input_name=''): + try: + ival = int(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires integer value: %s' % exp) + return ival + def gds_validate_integer(self, input_data, node=None, input_name=''): + try: + value = int(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires integer value') + return value + def gds_format_integer_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_integer_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + int(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of integer values') + return values + def gds_format_float(self, input_data, input_name=''): + return ('%.15f' % float(input_data)).rstrip('0') + def gds_parse_float(self, input_data, node=None, input_name=''): + try: + fval_ = float(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires float or double value: %s' % exp) + return fval_ + def gds_validate_float(self, input_data, node=None, input_name=''): + try: + value = float(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires float value') + return value + def gds_format_float_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_float_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + float(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of float values') + return values + def gds_format_decimal(self, input_data, input_name=''): + return_value = '%s' % input_data + if '.' in return_value: + return_value = return_value.rstrip('0') + if return_value.endswith('.'): + return_value = return_value.rstrip('.') + return return_value + def gds_parse_decimal(self, input_data, node=None, input_name=''): + try: + decimal_value = decimal_.Decimal(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires decimal value') + return decimal_value + def gds_validate_decimal(self, input_data, node=None, input_name=''): + try: + value = decimal_.Decimal(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires decimal value') + return value + def gds_format_decimal_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return ' '.join([self.gds_format_decimal(item) for item in input_data]) + def gds_validate_decimal_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + decimal_.Decimal(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of decimal values') + return values + def gds_format_double(self, input_data, input_name=''): + return '%s' % input_data + def gds_parse_double(self, input_data, node=None, input_name=''): + try: + fval_ = float(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires double or float value: %s' % exp) + return fval_ + def gds_validate_double(self, input_data, node=None, input_name=''): + try: + value = float(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires double or float value') + return value + def gds_format_double_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_double_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + float(value) + except (TypeError, ValueError): + raise_parse_error( + node, 'Requires sequence of double or float values') + return values + def gds_format_boolean(self, input_data, input_name=''): + return ('%s' % input_data).lower() + def gds_parse_boolean(self, input_data, node=None, input_name=''): + input_data = input_data.strip() + if input_data in ('true', '1'): + bval = True + elif input_data in ('false', '0'): + bval = False + else: + raise_parse_error(node, 'Requires boolean value') + return bval + def gds_validate_boolean(self, input_data, node=None, input_name=''): + if input_data not in (True, 1, False, 0, ): + raise_parse_error( + node, + 'Requires boolean value ' + '(one of True, 1, False, 0)') + return input_data + def gds_format_boolean_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_boolean_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + value = self.gds_parse_boolean(value, node, input_name) + if value not in (True, 1, False, 0, ): + raise_parse_error( + node, + 'Requires sequence of boolean values ' + '(one of True, 1, False, 0)') + return values + def gds_validate_datetime(self, input_data, node=None, input_name=''): + return input_data + def gds_format_datetime(self, input_data, input_name=''): + if input_data.microsecond == 0: + _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( + input_data.year, + input_data.month, + input_data.day, + input_data.hour, + input_data.minute, + input_data.second, + ) + else: + _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( + input_data.year, + input_data.month, + input_data.day, + input_data.hour, + input_data.minute, + input_data.second, + ('%f' % (float(input_data.microsecond) / 1000000))[2:], + ) + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) + return _svalue + @classmethod + def gds_parse_datetime(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + time_parts = input_data.split('.') + if len(time_parts) > 1: + micro_seconds = int(float('0.' + time_parts[1]) * 1000000) + input_data = '%s.%s' % ( + time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) + dt = datetime_.datetime.strptime( + input_data, '%Y-%m-%dT%H:%M:%S.%f') + else: + dt = datetime_.datetime.strptime( + input_data, '%Y-%m-%dT%H:%M:%S') + dt = dt.replace(tzinfo=tz) + return dt + def gds_validate_date(self, input_data, node=None, input_name=''): + return input_data + def gds_format_date(self, input_data, input_name=''): + _svalue = '%04d-%02d-%02d' % ( + input_data.year, + input_data.month, + input_data.day, + ) + try: + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format( + hours, minutes) + except AttributeError: + pass + return _svalue + @classmethod + def gds_parse_date(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') + dt = dt.replace(tzinfo=tz) + return dt.date() + def gds_validate_time(self, input_data, node=None, input_name=''): + return input_data + def gds_format_time(self, input_data, input_name=''): + if input_data.microsecond == 0: + _svalue = '%02d:%02d:%02d' % ( + input_data.hour, + input_data.minute, + input_data.second, + ) + else: + _svalue = '%02d:%02d:%02d.%s' % ( + input_data.hour, + input_data.minute, + input_data.second, + ('%f' % (float(input_data.microsecond) / 1000000))[2:], + ) + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) + return _svalue + def gds_validate_simple_patterns(self, patterns, target): + # pat is a list of lists of strings/patterns. + # The target value must match at least one of the patterns + # in order for the test to succeed. + found1 = True + target = str(target) + for patterns1 in patterns: + found2 = False + for patterns2 in patterns1: + mo = re_.search(patterns2, target) + if mo is not None and len(mo.group(0)) == len(target): + found2 = True + break + if not found2: + found1 = False + break + return found1 + @classmethod + def gds_parse_time(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + if len(input_data.split('.')) > 1: + dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') + else: + dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') + dt = dt.replace(tzinfo=tz) + return dt.time() + def gds_check_cardinality_( + self, value, input_name, + min_occurs=0, max_occurs=1, required=None): + if value is None: + length = 0 + elif isinstance(value, list): + length = len(value) + else: + length = 1 + if required is not None : + if required and length < 1: + self.gds_collector_.add_message( + "Required value {}{} is missing".format( + input_name, self.gds_get_node_lineno_())) + if length < min_occurs: + self.gds_collector_.add_message( + "Number of values for {}{} is below " + "the minimum allowed, " + "expected at least {}, found {}".format( + input_name, self.gds_get_node_lineno_(), + min_occurs, length)) + elif length > max_occurs: + self.gds_collector_.add_message( + "Number of values for {}{} is above " + "the maximum allowed, " + "expected at most {}, found {}".format( + input_name, self.gds_get_node_lineno_(), + max_occurs, length)) + def gds_validate_builtin_ST_( + self, validator, value, input_name, + min_occurs=None, max_occurs=None, required=None): + if value is not None: + try: + validator(value, input_name=input_name) + except GDSParseError as parse_error: + self.gds_collector_.add_message(str(parse_error)) + def gds_validate_defined_ST_( + self, validator, value, input_name, + min_occurs=None, max_occurs=None, required=None): + if value is not None: + try: + validator(value) + except GDSParseError as parse_error: + self.gds_collector_.add_message(str(parse_error)) + def gds_str_lower(self, instring): + return instring.lower() + def get_path_(self, node): + path_list = [] + self.get_path_list_(node, path_list) + path_list.reverse() + path = '/'.join(path_list) + return path + Tag_strip_pattern_ = re_.compile(r'\{.*\}') + def get_path_list_(self, node, path_list): + if node is None: + return + tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) + if tag: + path_list.append(tag) + self.get_path_list_(node.getparent(), path_list) + def get_class_obj_(self, node, default_class=None): + class_obj1 = default_class + if 'xsi' in node.nsmap: + classname = node.get('{%s}type' % node.nsmap['xsi']) + if classname is not None: + names = classname.split(':') + if len(names) == 2: + classname = names[1] + class_obj2 = globals().get(classname) + if class_obj2 is not None: + class_obj1 = class_obj2 + return class_obj1 + def gds_build_any(self, node, type_name=None): + # provide default value in case option --disable-xml is used. + content = "" + content = etree_.tostring(node, encoding="unicode") + return content + @classmethod + def gds_reverse_node_mapping(cls, mapping): + return dict(((v, k) for k, v in mapping.items())) + @staticmethod + def gds_encode(instring): + if sys.version_info.major == 2: + if ExternalEncoding: + encoding = ExternalEncoding + else: + encoding = 'utf-8' + return instring.encode(encoding) + else: + return instring + @staticmethod + def convert_unicode(instring): + if isinstance(instring, str): + result = quote_xml(instring) + elif sys.version_info.major == 2 and isinstance(instring, unicode): + result = quote_xml(instring).encode('utf8') + else: + result = GeneratedsSuper.gds_encode(str(instring)) + return result + def __eq__(self, other): + def excl_select_objs_(obj): + return (obj[0] != 'parent_object_' and + obj[0] != 'gds_collector_') + if type(self) != type(other): + return False + return all(x == y for x, y in zip_longest( + filter(excl_select_objs_, self.__dict__.items()), + filter(excl_select_objs_, other.__dict__.items()))) + def __ne__(self, other): + return not self.__eq__(other) + # Django ETL transform hooks. + def gds_djo_etl_transform(self): + pass + def gds_djo_etl_transform_db_obj(self, dbobj): + pass + # SQLAlchemy ETL transform hooks. + def gds_sqa_etl_transform(self): + return 0, None + def gds_sqa_etl_transform_db_obj(self, dbobj): + pass + def gds_get_node_lineno_(self): + if (hasattr(self, "gds_elementtree_node_") and + self.gds_elementtree_node_ is not None): + return ' near line {}'.format( + self.gds_elementtree_node_.sourceline) + else: + return "" + + + def getSubclassFromModule_(module, class_): + '''Get the subclass of a class from a specific module.''' + name = class_.__name__ + 'Sub' + if hasattr(module, name): + return getattr(module, name) + else: + return None + + +# +# If you have installed IPython you can uncomment and use the following. +# IPython is available from http://ipython.scipy.org/. +# + +## from IPython.Shell import IPShellEmbed +## args = '' +## ipshell = IPShellEmbed(args, +## banner = 'Dropping into IPython', +## exit_msg = 'Leaving Interpreter, back to program.') + +# Then use the following line where and when you want to drop into the +# IPython shell: +# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') + +# +# Globals +# + +ExternalEncoding = '' +# Set this to false in order to deactivate during export, the use of +# name space prefixes captured from the input document. +UseCapturedNS_ = True +CapturedNsmap_ = {} +Tag_pattern_ = re_.compile(r'({.*})?(.*)') +String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") +Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') +CDATA_pattern_ = re_.compile(r"", re_.DOTALL) + +# Change this to redirect the generated superclass module to use a +# specific subclass module. +CurrentSubclassModule_ = None + +# +# Support/utility functions. +# + + +def showIndent(outfile, level, pretty_print=True): + if pretty_print: + for idx in range(level): + outfile.write(' ') + + +def quote_xml(inStr): + "Escape markup chars, but do not modify CDATA sections." + if not inStr: + return '' + s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) + s2 = '' + pos = 0 + matchobjects = CDATA_pattern_.finditer(s1) + for mo in matchobjects: + s3 = s1[pos:mo.start()] + s2 += quote_xml_aux(s3) + s2 += s1[mo.start():mo.end()] + pos = mo.end() + s3 = s1[pos:] + s2 += quote_xml_aux(s3) + return s2 + + +def quote_xml_aux(inStr): + s1 = inStr.replace('&', '&') + s1 = s1.replace('<', '<') + s1 = s1.replace('>', '>') + return s1 + + +def quote_attrib(inStr): + s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) + s1 = s1.replace('&', '&') + s1 = s1.replace('<', '<') + s1 = s1.replace('>', '>') + s1 = s1.replace('\n', ' ') + if '"' in s1: + if "'" in s1: + s1 = '"%s"' % s1.replace('"', """) + else: + s1 = "'%s'" % s1 + else: + s1 = '"%s"' % s1 + return s1 + + +def quote_python(inStr): + s1 = inStr + if s1.find("'") == -1: + if s1.find('\n') == -1: + return "'%s'" % s1 + else: + return "'''%s'''" % s1 + else: + if s1.find('"') != -1: + s1 = s1.replace('"', '\\"') + if s1.find('\n') == -1: + return '"%s"' % s1 + else: + return '"""%s"""' % s1 + + +def get_all_text_(node): + if node.text is not None: + text = node.text + else: + text = '' + for child in node: + if child.tail is not None: + text += child.tail + return text + + +def find_attr_value_(attr_name, node): + attrs = node.attrib + attr_parts = attr_name.split(':') + value = None + if len(attr_parts) == 1: + value = attrs.get(attr_name) + elif len(attr_parts) == 2: + prefix, name = attr_parts + if prefix == 'xml': + namespace = 'http://www.w3.org/XML/1998/namespace' + else: + namespace = node.nsmap.get(prefix) + if namespace is not None: + value = attrs.get('{%s}%s' % (namespace, name, )) + return value + + +def encode_str_2_3(instr): + return instr + + +class GDSParseError(Exception): + pass + + +def raise_parse_error(node, msg): + if node is not None: + msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) + raise GDSParseError(msg) + + +class MixedContainer: + # Constants for category: + CategoryNone = 0 + CategoryText = 1 + CategorySimple = 2 + CategoryComplex = 3 + # Constants for content_type: + TypeNone = 0 + TypeText = 1 + TypeString = 2 + TypeInteger = 3 + TypeFloat = 4 + TypeDecimal = 5 + TypeDouble = 6 + TypeBoolean = 7 + TypeBase64 = 8 + def __init__(self, category, content_type, name, value): + self.category = category + self.content_type = content_type + self.name = name + self.value = value + def getCategory(self): + return self.category + def getContenttype(self, content_type): + return self.content_type + def getValue(self): + return self.value + def getName(self): + return self.name + def export(self, outfile, level, name, namespace, + pretty_print=True): + if self.category == MixedContainer.CategoryText: + # Prevent exporting empty content as empty lines. + if self.value.strip(): + outfile.write(self.value) + elif self.category == MixedContainer.CategorySimple: + self.exportSimple(outfile, level, name) + else: # category == MixedContainer.CategoryComplex + self.value.export( + outfile, level, namespace, name_=name, + pretty_print=pretty_print) + def exportSimple(self, outfile, level, name): + if self.content_type == MixedContainer.TypeString: + outfile.write('<%s>%s' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeInteger or \ + self.content_type == MixedContainer.TypeBoolean: + outfile.write('<%s>%d' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeFloat or \ + self.content_type == MixedContainer.TypeDecimal: + outfile.write('<%s>%f' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeDouble: + outfile.write('<%s>%g' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeBase64: + outfile.write('<%s>%s' % ( + self.name, + base64.b64encode(self.value), + self.name)) + def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): + if self.category == MixedContainer.CategoryText: + # Prevent exporting empty content as empty lines. + if self.value.strip(): + if len(element) > 0: + if element[-1].tail is None: + element[-1].tail = self.value + else: + element[-1].tail += self.value + else: + if element.text is None: + element.text = self.value + else: + element.text += self.value + elif self.category == MixedContainer.CategorySimple: + subelement = etree_.SubElement( + element, '%s' % self.name) + subelement.text = self.to_etree_simple() + else: # category == MixedContainer.CategoryComplex + self.value.to_etree(element) + def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): + if self.content_type == MixedContainer.TypeString: + text = self.value + elif (self.content_type == MixedContainer.TypeInteger or + self.content_type == MixedContainer.TypeBoolean): + text = '%d' % self.value + elif (self.content_type == MixedContainer.TypeFloat or + self.content_type == MixedContainer.TypeDecimal): + text = '%f' % self.value + elif self.content_type == MixedContainer.TypeDouble: + text = '%g' % self.value + elif self.content_type == MixedContainer.TypeBase64: + text = '%s' % base64.b64encode(self.value) + return text + def exportLiteral(self, outfile, level, name): + if self.category == MixedContainer.CategoryText: + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( + self.category, self.content_type, + self.name, self.value)) + elif self.category == MixedContainer.CategorySimple: + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( + self.category, self.content_type, + self.name, self.value)) + else: # category == MixedContainer.CategoryComplex + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s",\n' % ( + self.category, self.content_type, self.name,)) + self.value.exportLiteral(outfile, level + 1) + showIndent(outfile, level) + outfile.write(')\n') + + +class MemberSpec_(object): + def __init__(self, name='', data_type='', container=0, + optional=0, child_attrs=None, choice=None): + self.name = name + self.data_type = data_type + self.container = container + self.child_attrs = child_attrs + self.choice = choice + self.optional = optional + def set_name(self, name): self.name = name + def get_name(self): return self.name + def set_data_type(self, data_type): self.data_type = data_type + def get_data_type_chain(self): return self.data_type + def get_data_type(self): + if isinstance(self.data_type, list): + if len(self.data_type) > 0: + return self.data_type[-1] + else: + return 'xs:string' + else: + return self.data_type + def set_container(self, container): self.container = container + def get_container(self): return self.container + def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs + def get_child_attrs(self): return self.child_attrs + def set_choice(self, choice): self.choice = choice + def get_choice(self): return self.choice + def set_optional(self, optional): self.optional = optional + def get_optional(self): return self.optional + + +def _cast(typ, value): + if typ is None or value is None: + return value + return typ(value) + +# +# Data representation classes. +# + + +class NFeRecebidaPeriodo(GeneratedsSuper): + """DataInicial -- Intervalo inical de data em que a nota foi emitida para o tomador (AAAA-MM-DD). + DataFinal -- Data Final em que a nota foi emitida para o tomador (AAAA-MM-DD). + CPFCNPJPrestador -- CNPJ/CPF do Prestador do Servi + ç + o, ou seja, aquele que emitiu a nota ao Tomador + Pagina -- N + ú + mero da pagina que deseja consulta, caso a pesquisa excede o n + ú + mero de registros permitido o resultado + é + disponibilizado em p + á + ginas + + """ + __hash__ = GeneratedsSuper.__hash__ + subclass = None + superclass = None + def __init__(self, CPFCNPJTomador=None, DataInicial=None, DataFinal=None, CPFCNPJPrestador=None, Pagina=None, gds_collector_=None, **kwargs_): + self.gds_collector_ = gds_collector_ + self.gds_elementtree_node_ = None + self.original_tagname_ = None + self.parent_object_ = kwargs_.get('parent_object_') + self.ns_prefix_ = None + self.CPFCNPJTomador = CPFCNPJTomador + self.CPFCNPJTomador_nsprefix_ = None + if isinstance(DataInicial, BaseStrType_): + initvalue_ = datetime_.datetime.strptime(DataInicial, '%Y-%m-%d').date() + else: + initvalue_ = DataInicial + self.DataInicial = initvalue_ + self.DataInicial_nsprefix_ = None + if isinstance(DataFinal, BaseStrType_): + initvalue_ = datetime_.datetime.strptime(DataFinal, '%Y-%m-%d').date() + else: + initvalue_ = DataFinal + self.DataFinal = initvalue_ + self.DataFinal_nsprefix_ = None + self.CPFCNPJPrestador = CPFCNPJPrestador + self.CPFCNPJPrestador_nsprefix_ = None + self.Pagina = Pagina + self.Pagina_nsprefix_ = None + def factory(*args_, **kwargs_): + if CurrentSubclassModule_ is not None: + subclass = getSubclassFromModule_( + CurrentSubclassModule_, NFeRecebidaPeriodo) + if subclass is not None: + return subclass(*args_, **kwargs_) + if NFeRecebidaPeriodo.subclass: + return NFeRecebidaPeriodo.subclass(*args_, **kwargs_) + else: + return NFeRecebidaPeriodo(*args_, **kwargs_) + factory = staticmethod(factory) + def get_ns_prefix_(self): + return self.ns_prefix_ + def set_ns_prefix_(self, ns_prefix): + self.ns_prefix_ = ns_prefix + def get_CPFCNPJTomador(self): + return self.CPFCNPJTomador + def set_CPFCNPJTomador(self, CPFCNPJTomador): + self.CPFCNPJTomador = CPFCNPJTomador + def get_DataInicial(self): + return self.DataInicial + def set_DataInicial(self, DataInicial): + self.DataInicial = DataInicial + def get_DataFinal(self): + return self.DataFinal + def set_DataFinal(self, DataFinal): + self.DataFinal = DataFinal + def get_CPFCNPJPrestador(self): + return self.CPFCNPJPrestador + def set_CPFCNPJPrestador(self, CPFCNPJPrestador): + self.CPFCNPJPrestador = CPFCNPJPrestador + def get_Pagina(self): + return self.Pagina + def set_Pagina(self, Pagina): + self.Pagina = Pagina + def _hasContent(self): + if ( + self.CPFCNPJTomador is not None or + self.DataInicial is not None or + self.DataFinal is not None or + self.CPFCNPJPrestador is not None or + self.Pagina is not None + ): + return True + else: + return False + def export(self, outfile, level, namespaceprefix_='', namespacedef_=' xmlns:None="http://www.barueri.sp.gov.br/nfe" ', name_='NFeRecebidaPeriodo', pretty_print=True): + imported_ns_def_ = GenerateDSNamespaceDefs_.get('NFeRecebidaPeriodo') + if imported_ns_def_ is not None: + namespacedef_ = imported_ns_def_ + if pretty_print: + eol_ = '\n' + else: + eol_ = '' + if self.original_tagname_ is not None and name_ == 'NFeRecebidaPeriodo': + name_ = self.original_tagname_ + if UseCapturedNS_ and self.ns_prefix_: + namespaceprefix_ = self.ns_prefix_ + ':' + showIndent(outfile, level, pretty_print) + outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) + already_processed = set() + self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='NFeRecebidaPeriodo') + if self._hasContent(): + outfile.write('>%s' % (eol_, )) + self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='NFeRecebidaPeriodo', pretty_print=pretty_print) + showIndent(outfile, level, pretty_print) + outfile.write('%s' % (namespaceprefix_, name_, eol_)) + else: + outfile.write('/>%s' % (eol_, )) + def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='NFeRecebidaPeriodo'): + pass + def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_=' xmlns:None="http://www.barueri.sp.gov.br/nfe" ', name_='NFeRecebidaPeriodo', fromsubclass_=False, pretty_print=True): + if pretty_print: + eol_ = '\n' + else: + eol_ = '' + if self.CPFCNPJTomador is not None: + namespaceprefix_ = self.CPFCNPJTomador_nsprefix_ + ':' if (UseCapturedNS_ and self.CPFCNPJTomador_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sCPFCNPJTomador>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CPFCNPJTomador), input_name='CPFCNPJTomador')), namespaceprefix_ , eol_)) + if self.DataInicial is not None: + namespaceprefix_ = self.DataInicial_nsprefix_ + ':' if (UseCapturedNS_ and self.DataInicial_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sDataInicial>%s%s' % (namespaceprefix_ , self.gds_format_date(self.DataInicial, input_name='DataInicial'), namespaceprefix_ , eol_)) + if self.DataFinal is not None: + namespaceprefix_ = self.DataFinal_nsprefix_ + ':' if (UseCapturedNS_ and self.DataFinal_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sDataFinal>%s%s' % (namespaceprefix_ , self.gds_format_date(self.DataFinal, input_name='DataFinal'), namespaceprefix_ , eol_)) + if self.CPFCNPJPrestador is not None: + namespaceprefix_ = self.CPFCNPJPrestador_nsprefix_ + ':' if (UseCapturedNS_ and self.CPFCNPJPrestador_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sCPFCNPJPrestador>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CPFCNPJPrestador), input_name='CPFCNPJPrestador')), namespaceprefix_ , eol_)) + if self.Pagina is not None: + namespaceprefix_ = self.Pagina_nsprefix_ + ':' if (UseCapturedNS_ and self.Pagina_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sPagina>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Pagina, input_name='Pagina'), namespaceprefix_ , eol_)) + def build(self, node, gds_collector_=None): + self.gds_collector_ = gds_collector_ + if SaveElementTreeNode: + self.gds_elementtree_node_ = node + already_processed = set() + self.ns_prefix_ = node.prefix + self._buildAttributes(node, node.attrib, already_processed) + for child in node: + nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] + self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) + return self + def _buildAttributes(self, node, attrs, already_processed): + pass + def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): + if nodeName_ == 'CPFCNPJTomador': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'CPFCNPJTomador') + value_ = self.gds_validate_string(value_, node, 'CPFCNPJTomador') + self.CPFCNPJTomador = value_ + self.CPFCNPJTomador_nsprefix_ = child_.prefix + elif nodeName_ == 'DataInicial': + sval_ = child_.text + dval_ = self.gds_parse_date(sval_) + self.DataInicial = dval_ + self.DataInicial_nsprefix_ = child_.prefix + elif nodeName_ == 'DataFinal': + sval_ = child_.text + dval_ = self.gds_parse_date(sval_) + self.DataFinal = dval_ + self.DataFinal_nsprefix_ = child_.prefix + elif nodeName_ == 'CPFCNPJPrestador': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'CPFCNPJPrestador') + value_ = self.gds_validate_string(value_, node, 'CPFCNPJPrestador') + self.CPFCNPJPrestador = value_ + self.CPFCNPJPrestador_nsprefix_ = child_.prefix + elif nodeName_ == 'Pagina' and child_.text: + sval_ = child_.text + ival_ = self.gds_parse_integer(sval_, node, 'Pagina') + ival_ = self.gds_validate_integer(ival_, node, 'Pagina') + self.Pagina = ival_ + self.Pagina_nsprefix_ = child_.prefix +# end class NFeRecebidaPeriodo + + +GDSClassesMapping = { +} + + +USAGE_TEXT = """ +Usage: python .py [ -s ] +""" + + +def usage(): + print(USAGE_TEXT) + sys.exit(1) + + +def get_root_tag(node): + tag = Tag_pattern_.match(node.tag).groups()[-1] + prefix_tag = TagNamePrefix + tag + rootClass = GDSClassesMapping.get(prefix_tag) + if rootClass is None: + rootClass = globals().get(prefix_tag) + return tag, rootClass + + +def get_required_ns_prefix_defs(rootNode): + '''Get all name space prefix definitions required in this XML doc. + Return a dictionary of definitions and a char string of definitions. + ''' + nsmap = { + prefix: uri + for node in rootNode.iter() + for (prefix, uri) in node.nsmap.items() + if prefix is not None + } + namespacedefs = ' '.join([ + 'xmlns:{}="{}"'.format(prefix, uri) + for prefix, uri in nsmap.items() + ]) + return nsmap, namespacedefs + + +def parse(inFileName, silence=False, print_warnings=True): + global CapturedNsmap_ + gds_collector = GdsCollector_() + parser = None + doc = parsexml_(inFileName, parser) + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeRecebidaPeriodo' + rootClass = NFeRecebidaPeriodo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + sys.stdout.write('\n') + rootObj.export( + sys.stdout, 0, name_=rootTag, + namespacedef_=namespacedefs, + pretty_print=True) + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def parseEtree(inFileName, silence=False, print_warnings=True, + mapping=None, reverse_mapping=None, nsmap=None): + parser = None + doc = parsexml_(inFileName, parser) + gds_collector = GdsCollector_() + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeRecebidaPeriodo' + rootClass = NFeRecebidaPeriodo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + if mapping is None: + mapping = {} + if reverse_mapping is None: + reverse_mapping = {} + rootElement = rootObj.to_etree( + None, name_=rootTag, mapping_=mapping, + reverse_mapping_=reverse_mapping, nsmap_=nsmap) + reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) + # Enable Python to collect the space used by the DOM. + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + content = etree_.tostring( + rootElement, pretty_print=True, + xml_declaration=True, encoding="utf-8") + sys.stdout.write(str(content)) + sys.stdout.write('\n') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj, rootElement, mapping, reverse_node_mapping + + +def parseString(inString, silence=False, print_warnings=True): + '''Parse a string, create the object tree, and export it. + + Arguments: + - inString -- A string. This XML fragment should not start + with an XML declaration containing an encoding. + - silence -- A boolean. If False, export the object. + Returns -- The root object in the tree. + ''' + parser = None + rootNode= parsexmlstring_(inString, parser) + gds_collector = GdsCollector_() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeRecebidaPeriodo' + rootClass = NFeRecebidaPeriodo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + if not SaveElementTreeNode: + rootNode = None + if not silence: + sys.stdout.write('\n') + rootObj.export( + sys.stdout, 0, name_=rootTag, + namespacedef_='') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def parseLiteral(inFileName, silence=False, print_warnings=True): + parser = None + doc = parsexml_(inFileName, parser) + gds_collector = GdsCollector_() + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeRecebidaPeriodo' + rootClass = NFeRecebidaPeriodo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + # Enable Python to collect the space used by the DOM. + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + sys.stdout.write('#from ConsultarNFeRecebidaPeriodo import *\n\n') + sys.stdout.write('import ConsultarNFeRecebidaPeriodo as model_\n\n') + sys.stdout.write('rootObj = model_.rootClass(\n') + rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) + sys.stdout.write(')\n') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def main(): + args = sys.argv[1:] + if len(args) == 1: + parse(args[0]) + else: + usage() + + +if __name__ == '__main__': + #import pdb; pdb.set_trace() + main() + +RenameMappings_ = { +} + +# +# Mapping of namespaces to types defined in them +# and the file in which each is defined. +# simpleTypes are marked "ST" and complexTypes "CT". +NamespaceToDefMappings_ = {'http://www.barueri.sp.gov.br/nfe': []} + +__all__ = [ + "NFeRecebidaPeriodo" +] diff --git a/nfselib/barueri/NFeLoteBaixarArquivo.py b/nfselib/barueri/NFeLoteBaixarArquivo.py new file mode 100644 index 0000000..a1a2a8a --- /dev/null +++ b/nfselib/barueri/NFeLoteBaixarArquivo.py @@ -0,0 +1,1348 @@ +#TODO + +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# +# Generated Thu Apr 13 03:36:29 2023 by generateDS.py version 2.41.3. +# Python 3.8.10 (default, Mar 13 2023, 10:26:41) [GCC 9.4.0] +# +# Command line options: +# ('-o', 'NFeLoteBaixarArquivo.py') +# +# Command line arguments: +# ../../schemas/barueri/NFeLoteBaixarArquivo.v1.xsd +# +# Command line: +# /home/andre/.local/bin/generateDS -o "NFeLoteBaixarArquivo.py" ../../schemas/barueri/NFeLoteBaixarArquivo.v1.xsd +# +# Current working directory (os.getcwd()): +# barueri +# + +import sys +try: + ModulenotfoundExp_ = ModuleNotFoundError +except NameError: + ModulenotfoundExp_ = ImportError +from six.moves import zip_longest +import os +import re as re_ +import base64 +import datetime as datetime_ +import decimal as decimal_ +from lxml import etree as etree_ + + +Validate_simpletypes_ = True +SaveElementTreeNode = True +TagNamePrefix = "" +if sys.version_info.major == 2: + BaseStrType_ = basestring +else: + BaseStrType_ = str + + +def parsexml_(infile, parser=None, **kwargs): + if parser is None: + # Use the lxml ElementTree compatible parser so that, e.g., + # we ignore comments. + try: + parser = etree_.ETCompatXMLParser() + except AttributeError: + # fallback to xml.etree + parser = etree_.XMLParser() + try: + if isinstance(infile, os.PathLike): + infile = os.path.join(infile) + except AttributeError: + pass + doc = etree_.parse(infile, parser=parser, **kwargs) + return doc + +def parsexmlstring_(instring, parser=None, **kwargs): + if parser is None: + # Use the lxml ElementTree compatible parser so that, e.g., + # we ignore comments. + try: + parser = etree_.ETCompatXMLParser() + except AttributeError: + # fallback to xml.etree + parser = etree_.XMLParser() + element = etree_.fromstring(instring, parser=parser, **kwargs) + return element + +# +# Namespace prefix definition table (and other attributes, too) +# +# The module generatedsnamespaces, if it is importable, must contain +# a dictionary named GeneratedsNamespaceDefs. This Python dictionary +# should map element type names (strings) to XML schema namespace prefix +# definitions. The export method for any class for which there is +# a namespace prefix definition, will export that definition in the +# XML representation of that element. See the export method of +# any generated element type class for an example of the use of this +# table. +# A sample table is: +# +# # File: generatedsnamespaces.py +# +# GenerateDSNamespaceDefs = { +# "ElementtypeA": "http://www.xxx.com/namespaceA", +# "ElementtypeB": "http://www.xxx.com/namespaceB", +# } +# +# Additionally, the generatedsnamespaces module can contain a python +# dictionary named GenerateDSNamespaceTypePrefixes that associates element +# types with the namespace prefixes that are to be added to the +# "xsi:type" attribute value. See the _exportAttributes method of +# any generated element type and the generation of "xsi:type" for an +# example of the use of this table. +# An example table: +# +# # File: generatedsnamespaces.py +# +# GenerateDSNamespaceTypePrefixes = { +# "ElementtypeC": "aaa:", +# "ElementtypeD": "bbb:", +# } +# + +try: + from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ +except ModulenotfoundExp_ : + GenerateDSNamespaceDefs_ = {} +try: + from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ +except ModulenotfoundExp_ : + GenerateDSNamespaceTypePrefixes_ = {} + +# +# You can replace the following class definition by defining an +# importable module named "generatedscollector" containing a class +# named "GdsCollector". See the default class definition below for +# clues about the possible content of that class. +# +try: + from generatedscollector import GdsCollector as GdsCollector_ +except ModulenotfoundExp_ : + + class GdsCollector_(object): + + def __init__(self, messages=None): + if messages is None: + self.messages = [] + else: + self.messages = messages + + def add_message(self, msg): + self.messages.append(msg) + + def get_messages(self): + return self.messages + + def clear_messages(self): + self.messages = [] + + def print_messages(self): + for msg in self.messages: + print("Warning: {}".format(msg)) + + def write_messages(self, outstream): + for msg in self.messages: + outstream.write("Warning: {}\n".format(msg)) + + +# +# The super-class for enum types +# + +try: + from enum import Enum +except ModulenotfoundExp_ : + Enum = object + +# +# The root super-class for element type classes +# +# Calls to the methods in these classes are generated by generateDS.py. +# You can replace these methods by re-implementing the following class +# in a module named generatedssuper.py. + +try: + from generatedssuper import GeneratedsSuper +except ModulenotfoundExp_ as exp: + try: + from generatedssupersuper import GeneratedsSuperSuper + except ModulenotfoundExp_ as exp: + class GeneratedsSuperSuper(object): + pass + + class GeneratedsSuper(GeneratedsSuperSuper): + __hash__ = object.__hash__ + tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') + class _FixedOffsetTZ(datetime_.tzinfo): + def __init__(self, offset, name): + self.__offset = datetime_.timedelta(minutes=offset) + self.__name = name + def utcoffset(self, dt): + return self.__offset + def tzname(self, dt): + return self.__name + def dst(self, dt): + return None + def __str__(self): + settings = { + 'str_pretty_print': True, + 'str_indent_level': 0, + 'str_namespaceprefix': '', + 'str_name': self.__class__.__name__, + 'str_namespacedefs': '', + } + for n in settings: + if hasattr(self, n): + settings[n] = getattr(self, n) + if sys.version_info.major == 2: + from StringIO import StringIO + else: + from io import StringIO + output = StringIO() + self.export( + output, + settings['str_indent_level'], + pretty_print=settings['str_pretty_print'], + namespaceprefix_=settings['str_namespaceprefix'], + name_=settings['str_name'], + namespacedef_=settings['str_namespacedefs'] + ) + strval = output.getvalue() + output.close() + return strval + def gds_format_string(self, input_data, input_name=''): + return input_data + def gds_parse_string(self, input_data, node=None, input_name=''): + return input_data + def gds_validate_string(self, input_data, node=None, input_name=''): + if not input_data: + return '' + else: + return input_data + def gds_format_base64(self, input_data, input_name=''): + return base64.b64encode(input_data).decode('ascii') + def gds_validate_base64(self, input_data, node=None, input_name=''): + return input_data + def gds_format_integer(self, input_data, input_name=''): + return '%d' % int(input_data) + def gds_parse_integer(self, input_data, node=None, input_name=''): + try: + ival = int(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires integer value: %s' % exp) + return ival + def gds_validate_integer(self, input_data, node=None, input_name=''): + try: + value = int(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires integer value') + return value + def gds_format_integer_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_integer_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + int(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of integer values') + return values + def gds_format_float(self, input_data, input_name=''): + return ('%.15f' % float(input_data)).rstrip('0') + def gds_parse_float(self, input_data, node=None, input_name=''): + try: + fval_ = float(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires float or double value: %s' % exp) + return fval_ + def gds_validate_float(self, input_data, node=None, input_name=''): + try: + value = float(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires float value') + return value + def gds_format_float_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_float_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + float(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of float values') + return values + def gds_format_decimal(self, input_data, input_name=''): + return_value = '%s' % input_data + if '.' in return_value: + return_value = return_value.rstrip('0') + if return_value.endswith('.'): + return_value = return_value.rstrip('.') + return return_value + def gds_parse_decimal(self, input_data, node=None, input_name=''): + try: + decimal_value = decimal_.Decimal(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires decimal value') + return decimal_value + def gds_validate_decimal(self, input_data, node=None, input_name=''): + try: + value = decimal_.Decimal(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires decimal value') + return value + def gds_format_decimal_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return ' '.join([self.gds_format_decimal(item) for item in input_data]) + def gds_validate_decimal_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + decimal_.Decimal(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of decimal values') + return values + def gds_format_double(self, input_data, input_name=''): + return '%s' % input_data + def gds_parse_double(self, input_data, node=None, input_name=''): + try: + fval_ = float(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires double or float value: %s' % exp) + return fval_ + def gds_validate_double(self, input_data, node=None, input_name=''): + try: + value = float(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires double or float value') + return value + def gds_format_double_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_double_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + float(value) + except (TypeError, ValueError): + raise_parse_error( + node, 'Requires sequence of double or float values') + return values + def gds_format_boolean(self, input_data, input_name=''): + return ('%s' % input_data).lower() + def gds_parse_boolean(self, input_data, node=None, input_name=''): + input_data = input_data.strip() + if input_data in ('true', '1'): + bval = True + elif input_data in ('false', '0'): + bval = False + else: + raise_parse_error(node, 'Requires boolean value') + return bval + def gds_validate_boolean(self, input_data, node=None, input_name=''): + if input_data not in (True, 1, False, 0, ): + raise_parse_error( + node, + 'Requires boolean value ' + '(one of True, 1, False, 0)') + return input_data + def gds_format_boolean_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_boolean_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + value = self.gds_parse_boolean(value, node, input_name) + if value not in (True, 1, False, 0, ): + raise_parse_error( + node, + 'Requires sequence of boolean values ' + '(one of True, 1, False, 0)') + return values + def gds_validate_datetime(self, input_data, node=None, input_name=''): + return input_data + def gds_format_datetime(self, input_data, input_name=''): + if input_data.microsecond == 0: + _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( + input_data.year, + input_data.month, + input_data.day, + input_data.hour, + input_data.minute, + input_data.second, + ) + else: + _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( + input_data.year, + input_data.month, + input_data.day, + input_data.hour, + input_data.minute, + input_data.second, + ('%f' % (float(input_data.microsecond) / 1000000))[2:], + ) + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) + return _svalue + @classmethod + def gds_parse_datetime(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + time_parts = input_data.split('.') + if len(time_parts) > 1: + micro_seconds = int(float('0.' + time_parts[1]) * 1000000) + input_data = '%s.%s' % ( + time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) + dt = datetime_.datetime.strptime( + input_data, '%Y-%m-%dT%H:%M:%S.%f') + else: + dt = datetime_.datetime.strptime( + input_data, '%Y-%m-%dT%H:%M:%S') + dt = dt.replace(tzinfo=tz) + return dt + def gds_validate_date(self, input_data, node=None, input_name=''): + return input_data + def gds_format_date(self, input_data, input_name=''): + _svalue = '%04d-%02d-%02d' % ( + input_data.year, + input_data.month, + input_data.day, + ) + try: + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format( + hours, minutes) + except AttributeError: + pass + return _svalue + @classmethod + def gds_parse_date(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') + dt = dt.replace(tzinfo=tz) + return dt.date() + def gds_validate_time(self, input_data, node=None, input_name=''): + return input_data + def gds_format_time(self, input_data, input_name=''): + if input_data.microsecond == 0: + _svalue = '%02d:%02d:%02d' % ( + input_data.hour, + input_data.minute, + input_data.second, + ) + else: + _svalue = '%02d:%02d:%02d.%s' % ( + input_data.hour, + input_data.minute, + input_data.second, + ('%f' % (float(input_data.microsecond) / 1000000))[2:], + ) + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) + return _svalue + def gds_validate_simple_patterns(self, patterns, target): + # pat is a list of lists of strings/patterns. + # The target value must match at least one of the patterns + # in order for the test to succeed. + found1 = True + target = str(target) + for patterns1 in patterns: + found2 = False + for patterns2 in patterns1: + mo = re_.search(patterns2, target) + if mo is not None and len(mo.group(0)) == len(target): + found2 = True + break + if not found2: + found1 = False + break + return found1 + @classmethod + def gds_parse_time(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + if len(input_data.split('.')) > 1: + dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') + else: + dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') + dt = dt.replace(tzinfo=tz) + return dt.time() + def gds_check_cardinality_( + self, value, input_name, + min_occurs=0, max_occurs=1, required=None): + if value is None: + length = 0 + elif isinstance(value, list): + length = len(value) + else: + length = 1 + if required is not None : + if required and length < 1: + self.gds_collector_.add_message( + "Required value {}{} is missing".format( + input_name, self.gds_get_node_lineno_())) + if length < min_occurs: + self.gds_collector_.add_message( + "Number of values for {}{} is below " + "the minimum allowed, " + "expected at least {}, found {}".format( + input_name, self.gds_get_node_lineno_(), + min_occurs, length)) + elif length > max_occurs: + self.gds_collector_.add_message( + "Number of values for {}{} is above " + "the maximum allowed, " + "expected at most {}, found {}".format( + input_name, self.gds_get_node_lineno_(), + max_occurs, length)) + def gds_validate_builtin_ST_( + self, validator, value, input_name, + min_occurs=None, max_occurs=None, required=None): + if value is not None: + try: + validator(value, input_name=input_name) + except GDSParseError as parse_error: + self.gds_collector_.add_message(str(parse_error)) + def gds_validate_defined_ST_( + self, validator, value, input_name, + min_occurs=None, max_occurs=None, required=None): + if value is not None: + try: + validator(value) + except GDSParseError as parse_error: + self.gds_collector_.add_message(str(parse_error)) + def gds_str_lower(self, instring): + return instring.lower() + def get_path_(self, node): + path_list = [] + self.get_path_list_(node, path_list) + path_list.reverse() + path = '/'.join(path_list) + return path + Tag_strip_pattern_ = re_.compile(r'\{.*\}') + def get_path_list_(self, node, path_list): + if node is None: + return + tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) + if tag: + path_list.append(tag) + self.get_path_list_(node.getparent(), path_list) + def get_class_obj_(self, node, default_class=None): + class_obj1 = default_class + if 'xsi' in node.nsmap: + classname = node.get('{%s}type' % node.nsmap['xsi']) + if classname is not None: + names = classname.split(':') + if len(names) == 2: + classname = names[1] + class_obj2 = globals().get(classname) + if class_obj2 is not None: + class_obj1 = class_obj2 + return class_obj1 + def gds_build_any(self, node, type_name=None): + # provide default value in case option --disable-xml is used. + content = "" + content = etree_.tostring(node, encoding="unicode") + return content + @classmethod + def gds_reverse_node_mapping(cls, mapping): + return dict(((v, k) for k, v in mapping.items())) + @staticmethod + def gds_encode(instring): + if sys.version_info.major == 2: + if ExternalEncoding: + encoding = ExternalEncoding + else: + encoding = 'utf-8' + return instring.encode(encoding) + else: + return instring + @staticmethod + def convert_unicode(instring): + if isinstance(instring, str): + result = quote_xml(instring) + elif sys.version_info.major == 2 and isinstance(instring, unicode): + result = quote_xml(instring).encode('utf8') + else: + result = GeneratedsSuper.gds_encode(str(instring)) + return result + def __eq__(self, other): + def excl_select_objs_(obj): + return (obj[0] != 'parent_object_' and + obj[0] != 'gds_collector_') + if type(self) != type(other): + return False + return all(x == y for x, y in zip_longest( + filter(excl_select_objs_, self.__dict__.items()), + filter(excl_select_objs_, other.__dict__.items()))) + def __ne__(self, other): + return not self.__eq__(other) + # Django ETL transform hooks. + def gds_djo_etl_transform(self): + pass + def gds_djo_etl_transform_db_obj(self, dbobj): + pass + # SQLAlchemy ETL transform hooks. + def gds_sqa_etl_transform(self): + return 0, None + def gds_sqa_etl_transform_db_obj(self, dbobj): + pass + def gds_get_node_lineno_(self): + if (hasattr(self, "gds_elementtree_node_") and + self.gds_elementtree_node_ is not None): + return ' near line {}'.format( + self.gds_elementtree_node_.sourceline) + else: + return "" + + + def getSubclassFromModule_(module, class_): + '''Get the subclass of a class from a specific module.''' + name = class_.__name__ + 'Sub' + if hasattr(module, name): + return getattr(module, name) + else: + return None + + +# +# If you have installed IPython you can uncomment and use the following. +# IPython is available from http://ipython.scipy.org/. +# + +## from IPython.Shell import IPShellEmbed +## args = '' +## ipshell = IPShellEmbed(args, +## banner = 'Dropping into IPython', +## exit_msg = 'Leaving Interpreter, back to program.') + +# Then use the following line where and when you want to drop into the +# IPython shell: +# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') + +# +# Globals +# + +ExternalEncoding = '' +# Set this to false in order to deactivate during export, the use of +# name space prefixes captured from the input document. +UseCapturedNS_ = True +CapturedNsmap_ = {} +Tag_pattern_ = re_.compile(r'({.*})?(.*)') +String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") +Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') +CDATA_pattern_ = re_.compile(r"", re_.DOTALL) + +# Change this to redirect the generated superclass module to use a +# specific subclass module. +CurrentSubclassModule_ = None + +# +# Support/utility functions. +# + + +def showIndent(outfile, level, pretty_print=True): + if pretty_print: + for idx in range(level): + outfile.write(' ') + + +def quote_xml(inStr): + "Escape markup chars, but do not modify CDATA sections." + if not inStr: + return '' + s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) + s2 = '' + pos = 0 + matchobjects = CDATA_pattern_.finditer(s1) + for mo in matchobjects: + s3 = s1[pos:mo.start()] + s2 += quote_xml_aux(s3) + s2 += s1[mo.start():mo.end()] + pos = mo.end() + s3 = s1[pos:] + s2 += quote_xml_aux(s3) + return s2 + + +def quote_xml_aux(inStr): + s1 = inStr.replace('&', '&') + s1 = s1.replace('<', '<') + s1 = s1.replace('>', '>') + return s1 + + +def quote_attrib(inStr): + s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) + s1 = s1.replace('&', '&') + s1 = s1.replace('<', '<') + s1 = s1.replace('>', '>') + s1 = s1.replace('\n', ' ') + if '"' in s1: + if "'" in s1: + s1 = '"%s"' % s1.replace('"', """) + else: + s1 = "'%s'" % s1 + else: + s1 = '"%s"' % s1 + return s1 + + +def quote_python(inStr): + s1 = inStr + if s1.find("'") == -1: + if s1.find('\n') == -1: + return "'%s'" % s1 + else: + return "'''%s'''" % s1 + else: + if s1.find('"') != -1: + s1 = s1.replace('"', '\\"') + if s1.find('\n') == -1: + return '"%s"' % s1 + else: + return '"""%s"""' % s1 + + +def get_all_text_(node): + if node.text is not None: + text = node.text + else: + text = '' + for child in node: + if child.tail is not None: + text += child.tail + return text + + +def find_attr_value_(attr_name, node): + attrs = node.attrib + attr_parts = attr_name.split(':') + value = None + if len(attr_parts) == 1: + value = attrs.get(attr_name) + elif len(attr_parts) == 2: + prefix, name = attr_parts + if prefix == 'xml': + namespace = 'http://www.w3.org/XML/1998/namespace' + else: + namespace = node.nsmap.get(prefix) + if namespace is not None: + value = attrs.get('{%s}%s' % (namespace, name, )) + return value + + +def encode_str_2_3(instr): + return instr + + +class GDSParseError(Exception): + pass + + +def raise_parse_error(node, msg): + if node is not None: + msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) + raise GDSParseError(msg) + + +class MixedContainer: + # Constants for category: + CategoryNone = 0 + CategoryText = 1 + CategorySimple = 2 + CategoryComplex = 3 + # Constants for content_type: + TypeNone = 0 + TypeText = 1 + TypeString = 2 + TypeInteger = 3 + TypeFloat = 4 + TypeDecimal = 5 + TypeDouble = 6 + TypeBoolean = 7 + TypeBase64 = 8 + def __init__(self, category, content_type, name, value): + self.category = category + self.content_type = content_type + self.name = name + self.value = value + def getCategory(self): + return self.category + def getContenttype(self, content_type): + return self.content_type + def getValue(self): + return self.value + def getName(self): + return self.name + def export(self, outfile, level, name, namespace, + pretty_print=True): + if self.category == MixedContainer.CategoryText: + # Prevent exporting empty content as empty lines. + if self.value.strip(): + outfile.write(self.value) + elif self.category == MixedContainer.CategorySimple: + self.exportSimple(outfile, level, name) + else: # category == MixedContainer.CategoryComplex + self.value.export( + outfile, level, namespace, name_=name, + pretty_print=pretty_print) + def exportSimple(self, outfile, level, name): + if self.content_type == MixedContainer.TypeString: + outfile.write('<%s>%s' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeInteger or \ + self.content_type == MixedContainer.TypeBoolean: + outfile.write('<%s>%d' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeFloat or \ + self.content_type == MixedContainer.TypeDecimal: + outfile.write('<%s>%f' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeDouble: + outfile.write('<%s>%g' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeBase64: + outfile.write('<%s>%s' % ( + self.name, + base64.b64encode(self.value), + self.name)) + def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): + if self.category == MixedContainer.CategoryText: + # Prevent exporting empty content as empty lines. + if self.value.strip(): + if len(element) > 0: + if element[-1].tail is None: + element[-1].tail = self.value + else: + element[-1].tail += self.value + else: + if element.text is None: + element.text = self.value + else: + element.text += self.value + elif self.category == MixedContainer.CategorySimple: + subelement = etree_.SubElement( + element, '%s' % self.name) + subelement.text = self.to_etree_simple() + else: # category == MixedContainer.CategoryComplex + self.value.to_etree(element) + def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): + if self.content_type == MixedContainer.TypeString: + text = self.value + elif (self.content_type == MixedContainer.TypeInteger or + self.content_type == MixedContainer.TypeBoolean): + text = '%d' % self.value + elif (self.content_type == MixedContainer.TypeFloat or + self.content_type == MixedContainer.TypeDecimal): + text = '%f' % self.value + elif self.content_type == MixedContainer.TypeDouble: + text = '%g' % self.value + elif self.content_type == MixedContainer.TypeBase64: + text = '%s' % base64.b64encode(self.value) + return text + def exportLiteral(self, outfile, level, name): + if self.category == MixedContainer.CategoryText: + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( + self.category, self.content_type, + self.name, self.value)) + elif self.category == MixedContainer.CategorySimple: + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( + self.category, self.content_type, + self.name, self.value)) + else: # category == MixedContainer.CategoryComplex + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s",\n' % ( + self.category, self.content_type, self.name,)) + self.value.exportLiteral(outfile, level + 1) + showIndent(outfile, level) + outfile.write(')\n') + + +class MemberSpec_(object): + def __init__(self, name='', data_type='', container=0, + optional=0, child_attrs=None, choice=None): + self.name = name + self.data_type = data_type + self.container = container + self.child_attrs = child_attrs + self.choice = choice + self.optional = optional + def set_name(self, name): self.name = name + def get_name(self): return self.name + def set_data_type(self, data_type): self.data_type = data_type + def get_data_type_chain(self): return self.data_type + def get_data_type(self): + if isinstance(self.data_type, list): + if len(self.data_type) > 0: + return self.data_type[-1] + else: + return 'xs:string' + else: + return self.data_type + def set_container(self, container): self.container = container + def get_container(self): return self.container + def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs + def get_child_attrs(self): return self.child_attrs + def set_choice(self, choice): self.choice = choice + def get_choice(self): return self.choice + def set_optional(self, optional): self.optional = optional + def get_optional(self): return self.optional + + +def _cast(typ, value): + if typ is None or value is None: + return value + return typ(value) + +# +# Data representation classes. +# + + +class NFeLoteBaixarArquivo(GeneratedsSuper): + """InscricaoMunicipal -- Numero da inscri + ç + ã + o municipal do contribuinte na Prefeitura de Barueri. + CPFCNPJContrib -- CNPJ/CPF do contribuinte + NomeArqRetorno -- Nome do Arquivo de retorno que deseja baixar. Para obter a rela + ç + ã + o de arquivos a serem baixado utilize o m + é + todo NFeLoteListarArquivos + + """ + __hash__ = GeneratedsSuper.__hash__ + subclass = None + superclass = None + def __init__(self, InscricaoMunicipal=None, CPFCNPJContrib=None, NomeArqRetorno=None, gds_collector_=None, **kwargs_): + self.gds_collector_ = gds_collector_ + self.gds_elementtree_node_ = None + self.original_tagname_ = None + self.parent_object_ = kwargs_.get('parent_object_') + self.ns_prefix_ = None + self.InscricaoMunicipal = InscricaoMunicipal + self.InscricaoMunicipal_nsprefix_ = None + self.CPFCNPJContrib = CPFCNPJContrib + self.CPFCNPJContrib_nsprefix_ = None + self.NomeArqRetorno = NomeArqRetorno + self.NomeArqRetorno_nsprefix_ = None + def factory(*args_, **kwargs_): + if CurrentSubclassModule_ is not None: + subclass = getSubclassFromModule_( + CurrentSubclassModule_, NFeLoteBaixarArquivo) + if subclass is not None: + return subclass(*args_, **kwargs_) + if NFeLoteBaixarArquivo.subclass: + return NFeLoteBaixarArquivo.subclass(*args_, **kwargs_) + else: + return NFeLoteBaixarArquivo(*args_, **kwargs_) + factory = staticmethod(factory) + def get_ns_prefix_(self): + return self.ns_prefix_ + def set_ns_prefix_(self, ns_prefix): + self.ns_prefix_ = ns_prefix + def get_InscricaoMunicipal(self): + return self.InscricaoMunicipal + def set_InscricaoMunicipal(self, InscricaoMunicipal): + self.InscricaoMunicipal = InscricaoMunicipal + def get_CPFCNPJContrib(self): + return self.CPFCNPJContrib + def set_CPFCNPJContrib(self, CPFCNPJContrib): + self.CPFCNPJContrib = CPFCNPJContrib + def get_NomeArqRetorno(self): + return self.NomeArqRetorno + def set_NomeArqRetorno(self, NomeArqRetorno): + self.NomeArqRetorno = NomeArqRetorno + def _hasContent(self): + if ( + self.InscricaoMunicipal is not None or + self.CPFCNPJContrib is not None or + self.NomeArqRetorno is not None + ): + return True + else: + return False + def export(self, outfile, level, namespaceprefix_='', namespacedef_=' xmlns:None="http://www.barueri.sp.gov.br/nfe" ', name_='NFeLoteBaixarArquivo', pretty_print=True): + imported_ns_def_ = GenerateDSNamespaceDefs_.get('NFeLoteBaixarArquivo') + if imported_ns_def_ is not None: + namespacedef_ = imported_ns_def_ + if pretty_print: + eol_ = '\n' + else: + eol_ = '' + if self.original_tagname_ is not None and name_ == 'NFeLoteBaixarArquivo': + name_ = self.original_tagname_ + if UseCapturedNS_ and self.ns_prefix_: + namespaceprefix_ = self.ns_prefix_ + ':' + showIndent(outfile, level, pretty_print) + outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) + already_processed = set() + self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='NFeLoteBaixarArquivo') + if self._hasContent(): + outfile.write('>%s' % (eol_, )) + self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='NFeLoteBaixarArquivo', pretty_print=pretty_print) + showIndent(outfile, level, pretty_print) + outfile.write('%s' % (namespaceprefix_, name_, eol_)) + else: + outfile.write('/>%s' % (eol_, )) + def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='NFeLoteBaixarArquivo'): + pass + def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_=' xmlns:None="http://www.barueri.sp.gov.br/nfe" ', name_='NFeLoteBaixarArquivo', fromsubclass_=False, pretty_print=True): + if pretty_print: + eol_ = '\n' + else: + eol_ = '' + if self.InscricaoMunicipal is not None: + namespaceprefix_ = self.InscricaoMunicipal_nsprefix_ + ':' if (UseCapturedNS_ and self.InscricaoMunicipal_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sInscricaoMunicipal>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InscricaoMunicipal), input_name='InscricaoMunicipal')), namespaceprefix_ , eol_)) + if self.CPFCNPJContrib is not None: + namespaceprefix_ = self.CPFCNPJContrib_nsprefix_ + ':' if (UseCapturedNS_ and self.CPFCNPJContrib_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sCPFCNPJContrib>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CPFCNPJContrib), input_name='CPFCNPJContrib')), namespaceprefix_ , eol_)) + if self.NomeArqRetorno is not None: + namespaceprefix_ = self.NomeArqRetorno_nsprefix_ + ':' if (UseCapturedNS_ and self.NomeArqRetorno_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sNomeArqRetorno>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.NomeArqRetorno), input_name='NomeArqRetorno')), namespaceprefix_ , eol_)) + def build(self, node, gds_collector_=None): + self.gds_collector_ = gds_collector_ + if SaveElementTreeNode: + self.gds_elementtree_node_ = node + already_processed = set() + self.ns_prefix_ = node.prefix + self._buildAttributes(node, node.attrib, already_processed) + for child in node: + nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] + self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) + return self + def _buildAttributes(self, node, attrs, already_processed): + pass + def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): + if nodeName_ == 'InscricaoMunicipal': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'InscricaoMunicipal') + value_ = self.gds_validate_string(value_, node, 'InscricaoMunicipal') + self.InscricaoMunicipal = value_ + self.InscricaoMunicipal_nsprefix_ = child_.prefix + elif nodeName_ == 'CPFCNPJContrib': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'CPFCNPJContrib') + value_ = self.gds_validate_string(value_, node, 'CPFCNPJContrib') + self.CPFCNPJContrib = value_ + self.CPFCNPJContrib_nsprefix_ = child_.prefix + elif nodeName_ == 'NomeArqRetorno': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'NomeArqRetorno') + value_ = self.gds_validate_string(value_, node, 'NomeArqRetorno') + self.NomeArqRetorno = value_ + self.NomeArqRetorno_nsprefix_ = child_.prefix +# end class NFeLoteBaixarArquivo + + +GDSClassesMapping = { +} + + +USAGE_TEXT = """ +Usage: python .py [ -s ] +""" + + +def usage(): + print(USAGE_TEXT) + sys.exit(1) + + +def get_root_tag(node): + tag = Tag_pattern_.match(node.tag).groups()[-1] + prefix_tag = TagNamePrefix + tag + rootClass = GDSClassesMapping.get(prefix_tag) + if rootClass is None: + rootClass = globals().get(prefix_tag) + return tag, rootClass + + +def get_required_ns_prefix_defs(rootNode): + '''Get all name space prefix definitions required in this XML doc. + Return a dictionary of definitions and a char string of definitions. + ''' + nsmap = { + prefix: uri + for node in rootNode.iter() + for (prefix, uri) in node.nsmap.items() + if prefix is not None + } + namespacedefs = ' '.join([ + 'xmlns:{}="{}"'.format(prefix, uri) + for prefix, uri in nsmap.items() + ]) + return nsmap, namespacedefs + + +def parse(inFileName, silence=False, print_warnings=True): + global CapturedNsmap_ + gds_collector = GdsCollector_() + parser = None + doc = parsexml_(inFileName, parser) + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteBaixarArquivo' + rootClass = NFeLoteBaixarArquivo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + sys.stdout.write('\n') + rootObj.export( + sys.stdout, 0, name_=rootTag, + namespacedef_=namespacedefs, + pretty_print=True) + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def parseEtree(inFileName, silence=False, print_warnings=True, + mapping=None, reverse_mapping=None, nsmap=None): + parser = None + doc = parsexml_(inFileName, parser) + gds_collector = GdsCollector_() + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteBaixarArquivo' + rootClass = NFeLoteBaixarArquivo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + if mapping is None: + mapping = {} + if reverse_mapping is None: + reverse_mapping = {} + rootElement = rootObj.to_etree( + None, name_=rootTag, mapping_=mapping, + reverse_mapping_=reverse_mapping, nsmap_=nsmap) + reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) + # Enable Python to collect the space used by the DOM. + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + content = etree_.tostring( + rootElement, pretty_print=True, + xml_declaration=True, encoding="utf-8") + sys.stdout.write(str(content)) + sys.stdout.write('\n') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj, rootElement, mapping, reverse_node_mapping + + +def parseString(inString, silence=False, print_warnings=True): + '''Parse a string, create the object tree, and export it. + + Arguments: + - inString -- A string. This XML fragment should not start + with an XML declaration containing an encoding. + - silence -- A boolean. If False, export the object. + Returns -- The root object in the tree. + ''' + parser = None + rootNode= parsexmlstring_(inString, parser) + gds_collector = GdsCollector_() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteBaixarArquivo' + rootClass = NFeLoteBaixarArquivo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + if not SaveElementTreeNode: + rootNode = None + if not silence: + sys.stdout.write('\n') + rootObj.export( + sys.stdout, 0, name_=rootTag, + namespacedef_='') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def parseLiteral(inFileName, silence=False, print_warnings=True): + parser = None + doc = parsexml_(inFileName, parser) + gds_collector = GdsCollector_() + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteBaixarArquivo' + rootClass = NFeLoteBaixarArquivo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + # Enable Python to collect the space used by the DOM. + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + sys.stdout.write('#from NFeLoteBaixarArquivo import *\n\n') + sys.stdout.write('import NFeLoteBaixarArquivo as model_\n\n') + sys.stdout.write('rootObj = model_.rootClass(\n') + rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) + sys.stdout.write(')\n') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def main(): + args = sys.argv[1:] + if len(args) == 1: + parse(args[0]) + else: + usage() + + +if __name__ == '__main__': + #import pdb; pdb.set_trace() + main() + +RenameMappings_ = { +} + +# +# Mapping of namespaces to types defined in them +# and the file in which each is defined. +# simpleTypes are marked "ST" and complexTypes "CT". +NamespaceToDefMappings_ = {'http://www.barueri.sp.gov.br/nfe': []} + +__all__ = [ + "NFeLoteBaixarArquivo" +] diff --git a/nfselib/barueri/NFeLoteEnviarArquivo.py b/nfselib/barueri/NFeLoteEnviarArquivo.py new file mode 100644 index 0000000..42323fd --- /dev/null +++ b/nfselib/barueri/NFeLoteEnviarArquivo.py @@ -0,0 +1,1415 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# +# Generated Thu Apr 13 03:27:47 2023 by generateDS.py version 2.41.3. +# Python 3.8.10 (default, Mar 13 2023, 10:26:41) [GCC 9.4.0] +# +# Command line options: +# ('-o', 'NFeLoteEnviarArquivo.py') +# +# Command line arguments: +# ../../schemas/barueri/NFeLoteEnviarArquivo.v1.xsd +# +# Command line: +# /home/andre/.local/bin/generateDS -o "NFeLoteEnviarArquivo.py" ../../schemas/barueri/NFeLoteEnviarArquivo.v1.xsd +# +# Current working directory (os.getcwd()): +# barueri +# + +import sys +try: + ModulenotfoundExp_ = ModuleNotFoundError +except NameError: + ModulenotfoundExp_ = ImportError +from six.moves import zip_longest +import os +import re as re_ +import base64 +import datetime as datetime_ +import decimal as decimal_ +from lxml import etree as etree_ +from .exportador import Arquivo + +Validate_simpletypes_ = True +SaveElementTreeNode = True +TagNamePrefix = "" +if sys.version_info.major == 2: + BaseStrType_ = basestring +else: + BaseStrType_ = str + + +def parsexml_(infile, parser=None, **kwargs): + if parser is None: + # Use the lxml ElementTree compatible parser so that, e.g., + # we ignore comments. + try: + parser = etree_.ETCompatXMLParser() + except AttributeError: + # fallback to xml.etree + parser = etree_.XMLParser() + try: + if isinstance(infile, os.PathLike): + infile = os.path.join(infile) + except AttributeError: + pass + doc = etree_.parse(infile, parser=parser, **kwargs) + return doc + +def parsexmlstring_(instring, parser=None, **kwargs): + if parser is None: + # Use the lxml ElementTree compatible parser so that, e.g., + # we ignore comments. + try: + parser = etree_.ETCompatXMLParser() + except AttributeError: + # fallback to xml.etree + parser = etree_.XMLParser() + element = etree_.fromstring(instring, parser=parser, **kwargs) + return element + +# +# Namespace prefix definition table (and other attributes, too) +# +# The module generatedsnamespaces, if it is importable, must contain +# a dictionary named GeneratedsNamespaceDefs. This Python dictionary +# should map element type names (strings) to XML schema namespace prefix +# definitions. The export method for any class for which there is +# a namespace prefix definition, will export that definition in the +# XML representation of that element. See the export method of +# any generated element type class for an example of the use of this +# table. +# A sample table is: +# +# # File: generatedsnamespaces.py +# +# GenerateDSNamespaceDefs = { +# "ElementtypeA": "http://www.xxx.com/namespaceA", +# "ElementtypeB": "http://www.xxx.com/namespaceB", +# } +# +# Additionally, the generatedsnamespaces module can contain a python +# dictionary named GenerateDSNamespaceTypePrefixes that associates element +# types with the namespace prefixes that are to be added to the +# "xsi:type" attribute value. See the _exportAttributes method of +# any generated element type and the generation of "xsi:type" for an +# example of the use of this table. +# An example table: +# +# # File: generatedsnamespaces.py +# +# GenerateDSNamespaceTypePrefixes = { +# "ElementtypeC": "aaa:", +# "ElementtypeD": "bbb:", +# } +# + +try: + from .generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ +except ModulenotfoundExp_ : + GenerateDSNamespaceDefs_ = {} +try: + from .generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ +except ModulenotfoundExp_ : + GenerateDSNamespaceTypePrefixes_ = {} + +# +# You can replace the following class definition by defining an +# importable module named "generatedscollector" containing a class +# named "GdsCollector". See the default class definition below for +# clues about the possible content of that class. +# +try: + from generatedscollector import GdsCollector as GdsCollector_ +except ModulenotfoundExp_ : + + class GdsCollector_(object): + + def __init__(self, messages=None): + if messages is None: + self.messages = [] + else: + self.messages = messages + + def add_message(self, msg): + self.messages.append(msg) + + def get_messages(self): + return self.messages + + def clear_messages(self): + self.messages = [] + + def print_messages(self): + for msg in self.messages: + print("Warning: {}".format(msg)) + + def write_messages(self, outstream): + for msg in self.messages: + outstream.write("Warning: {}\n".format(msg)) + + +# +# The super-class for enum types +# + +try: + from enum import Enum +except ModulenotfoundExp_ : + Enum = object + +# +# The root super-class for element type classes +# +# Calls to the methods in these classes are generated by generateDS.py. +# You can replace these methods by re-implementing the following class +# in a module named generatedssuper.py. + +try: + from generatedssuper import GeneratedsSuper +except ModulenotfoundExp_ as exp: + try: + from generatedssupersuper import GeneratedsSuperSuper + except ModulenotfoundExp_ as exp: + class GeneratedsSuperSuper(object): + pass + + class GeneratedsSuper(GeneratedsSuperSuper): + __hash__ = object.__hash__ + tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') + class _FixedOffsetTZ(datetime_.tzinfo): + def __init__(self, offset, name): + self.__offset = datetime_.timedelta(minutes=offset) + self.__name = name + def utcoffset(self, dt): + return self.__offset + def tzname(self, dt): + return self.__name + def dst(self, dt): + return None + def __str__(self): + settings = { + 'str_pretty_print': True, + 'str_indent_level': 0, + 'str_namespaceprefix': '', + 'str_name': self.__class__.__name__, + 'str_namespacedefs': '', + } + for n in settings: + if hasattr(self, n): + settings[n] = getattr(self, n) + if sys.version_info.major == 2: + from StringIO import StringIO + else: + from io import StringIO + output = StringIO() + self.export( + output, + settings['str_indent_level'], + pretty_print=settings['str_pretty_print'], + namespaceprefix_=settings['str_namespaceprefix'], + name_=settings['str_name'], + namespacedef_=settings['str_namespacedefs'] + ) + strval = output.getvalue() + output.close() + return strval + def gds_format_string(self, input_data, input_name=''): + return input_data + def gds_parse_string(self, input_data, node=None, input_name=''): + return input_data + def gds_validate_string(self, input_data, node=None, input_name=''): + if not input_data: + return '' + else: + return input_data + def gds_format_base64(self, input_data, input_name=''): + return base64.b64encode(input_data).decode('ascii') + def gds_validate_base64(self, input_data, node=None, input_name=''): + return input_data + def gds_format_integer(self, input_data, input_name=''): + return '%d' % int(input_data) + def gds_parse_integer(self, input_data, node=None, input_name=''): + try: + ival = int(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires integer value: %s' % exp) + return ival + def gds_validate_integer(self, input_data, node=None, input_name=''): + try: + value = int(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires integer value') + return value + def gds_format_integer_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_integer_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + int(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of integer values') + return values + def gds_format_float(self, input_data, input_name=''): + return ('%.15f' % float(input_data)).rstrip('0') + def gds_parse_float(self, input_data, node=None, input_name=''): + try: + fval_ = float(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires float or double value: %s' % exp) + return fval_ + def gds_validate_float(self, input_data, node=None, input_name=''): + try: + value = float(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires float value') + return value + def gds_format_float_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_float_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + float(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of float values') + return values + def gds_format_decimal(self, input_data, input_name=''): + return_value = '%s' % input_data + if '.' in return_value: + return_value = return_value.rstrip('0') + if return_value.endswith('.'): + return_value = return_value.rstrip('.') + return return_value + def gds_parse_decimal(self, input_data, node=None, input_name=''): + try: + decimal_value = decimal_.Decimal(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires decimal value') + return decimal_value + def gds_validate_decimal(self, input_data, node=None, input_name=''): + try: + value = decimal_.Decimal(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires decimal value') + return value + def gds_format_decimal_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return ' '.join([self.gds_format_decimal(item) for item in input_data]) + def gds_validate_decimal_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + decimal_.Decimal(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of decimal values') + return values + def gds_format_double(self, input_data, input_name=''): + return '%s' % input_data + def gds_parse_double(self, input_data, node=None, input_name=''): + try: + fval_ = float(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires double or float value: %s' % exp) + return fval_ + def gds_validate_double(self, input_data, node=None, input_name=''): + try: + value = float(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires double or float value') + return value + def gds_format_double_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_double_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + float(value) + except (TypeError, ValueError): + raise_parse_error( + node, 'Requires sequence of double or float values') + return values + def gds_format_boolean(self, input_data, input_name=''): + return ('%s' % input_data).lower() + def gds_parse_boolean(self, input_data, node=None, input_name=''): + input_data = input_data.strip() + if input_data in ('true', '1'): + bval = True + elif input_data in ('false', '0'): + bval = False + else: + raise_parse_error(node, 'Requires boolean value') + return bval + def gds_validate_boolean(self, input_data, node=None, input_name=''): + if input_data not in (True, 1, False, 0, ): + raise_parse_error( + node, + 'Requires boolean value ' + '(one of True, 1, False, 0)') + return input_data + def gds_format_boolean_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_boolean_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + value = self.gds_parse_boolean(value, node, input_name) + if value not in (True, 1, False, 0, ): + raise_parse_error( + node, + 'Requires sequence of boolean values ' + '(one of True, 1, False, 0)') + return values + def gds_validate_datetime(self, input_data, node=None, input_name=''): + return input_data + def gds_format_datetime(self, input_data, input_name=''): + if input_data.microsecond == 0: + _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( + input_data.year, + input_data.month, + input_data.day, + input_data.hour, + input_data.minute, + input_data.second, + ) + else: + _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( + input_data.year, + input_data.month, + input_data.day, + input_data.hour, + input_data.minute, + input_data.second, + ('%f' % (float(input_data.microsecond) / 1000000))[2:], + ) + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) + return _svalue + @classmethod + def gds_parse_datetime(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + time_parts = input_data.split('.') + if len(time_parts) > 1: + micro_seconds = int(float('0.' + time_parts[1]) * 1000000) + input_data = '%s.%s' % ( + time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) + dt = datetime_.datetime.strptime( + input_data, '%Y-%m-%dT%H:%M:%S.%f') + else: + dt = datetime_.datetime.strptime( + input_data, '%Y-%m-%dT%H:%M:%S') + dt = dt.replace(tzinfo=tz) + return dt + def gds_validate_date(self, input_data, node=None, input_name=''): + return input_data + def gds_format_date(self, input_data, input_name=''): + _svalue = '%04d-%02d-%02d' % ( + input_data.year, + input_data.month, + input_data.day, + ) + try: + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format( + hours, minutes) + except AttributeError: + pass + return _svalue + @classmethod + def gds_parse_date(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') + dt = dt.replace(tzinfo=tz) + return dt.date() + def gds_validate_time(self, input_data, node=None, input_name=''): + return input_data + def gds_format_time(self, input_data, input_name=''): + if input_data.microsecond == 0: + _svalue = '%02d:%02d:%02d' % ( + input_data.hour, + input_data.minute, + input_data.second, + ) + else: + _svalue = '%02d:%02d:%02d.%s' % ( + input_data.hour, + input_data.minute, + input_data.second, + ('%f' % (float(input_data.microsecond) / 1000000))[2:], + ) + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) + return _svalue + def gds_validate_simple_patterns(self, patterns, target): + # pat is a list of lists of strings/patterns. + # The target value must match at least one of the patterns + # in order for the test to succeed. + found1 = True + target = str(target) + for patterns1 in patterns: + found2 = False + for patterns2 in patterns1: + mo = re_.search(patterns2, target) + if mo is not None and len(mo.group(0)) == len(target): + found2 = True + break + if not found2: + found1 = False + break + return found1 + @classmethod + def gds_parse_time(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + if len(input_data.split('.')) > 1: + dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') + else: + dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') + dt = dt.replace(tzinfo=tz) + return dt.time() + def gds_check_cardinality_( + self, value, input_name, + min_occurs=0, max_occurs=1, required=None): + if value is None: + length = 0 + elif isinstance(value, list): + length = len(value) + else: + length = 1 + if required is not None : + if required and length < 1: + self.gds_collector_.add_message( + "Required value {}{} is missing".format( + input_name, self.gds_get_node_lineno_())) + if length < min_occurs: + self.gds_collector_.add_message( + "Number of values for {}{} is below " + "the minimum allowed, " + "expected at least {}, found {}".format( + input_name, self.gds_get_node_lineno_(), + min_occurs, length)) + elif length > max_occurs: + self.gds_collector_.add_message( + "Number of values for {}{} is above " + "the maximum allowed, " + "expected at most {}, found {}".format( + input_name, self.gds_get_node_lineno_(), + max_occurs, length)) + def gds_validate_builtin_ST_( + self, validator, value, input_name, + min_occurs=None, max_occurs=None, required=None): + if value is not None: + try: + validator(value, input_name=input_name) + except GDSParseError as parse_error: + self.gds_collector_.add_message(str(parse_error)) + def gds_validate_defined_ST_( + self, validator, value, input_name, + min_occurs=None, max_occurs=None, required=None): + if value is not None: + try: + validator(value) + except GDSParseError as parse_error: + self.gds_collector_.add_message(str(parse_error)) + def gds_str_lower(self, instring): + return instring.lower() + def get_path_(self, node): + path_list = [] + self.get_path_list_(node, path_list) + path_list.reverse() + path = '/'.join(path_list) + return path + Tag_strip_pattern_ = re_.compile(r'\{.*\}') + def get_path_list_(self, node, path_list): + if node is None: + return + tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) + if tag: + path_list.append(tag) + self.get_path_list_(node.getparent(), path_list) + def get_class_obj_(self, node, default_class=None): + class_obj1 = default_class + if 'xsi' in node.nsmap: + classname = node.get('{%s}type' % node.nsmap['xsi']) + if classname is not None: + names = classname.split(':') + if len(names) == 2: + classname = names[1] + class_obj2 = globals().get(classname) + if class_obj2 is not None: + class_obj1 = class_obj2 + return class_obj1 + def gds_build_any(self, node, type_name=None): + # provide default value in case option --disable-xml is used. + content = "" + content = etree_.tostring(node, encoding="unicode") + return content + @classmethod + def gds_reverse_node_mapping(cls, mapping): + return dict(((v, k) for k, v in mapping.items())) + @staticmethod + def gds_encode(instring): + if sys.version_info.major == 2: + if ExternalEncoding: + encoding = ExternalEncoding + else: + encoding = 'utf-8' + return instring.encode(encoding) + else: + return instring + @staticmethod + def convert_unicode(instring): + if isinstance(instring, str): + result = quote_xml(instring) + elif sys.version_info.major == 2 and isinstance(instring, unicode): + result = quote_xml(instring).encode('utf8') + else: + result = GeneratedsSuper.gds_encode(str(instring)) + return result + def __eq__(self, other): + def excl_select_objs_(obj): + return (obj[0] != 'parent_object_' and + obj[0] != 'gds_collector_') + if type(self) != type(other): + return False + return all(x == y for x, y in zip_longest( + filter(excl_select_objs_, self.__dict__.items()), + filter(excl_select_objs_, other.__dict__.items()))) + def __ne__(self, other): + return not self.__eq__(other) + # Django ETL transform hooks. + def gds_djo_etl_transform(self): + pass + def gds_djo_etl_transform_db_obj(self, dbobj): + pass + # SQLAlchemy ETL transform hooks. + def gds_sqa_etl_transform(self): + return 0, None + def gds_sqa_etl_transform_db_obj(self, dbobj): + pass + def gds_get_node_lineno_(self): + if (hasattr(self, "gds_elementtree_node_") and + self.gds_elementtree_node_ is not None): + return ' near line {}'.format( + self.gds_elementtree_node_.sourceline) + else: + return "" + + + def getSubclassFromModule_(module, class_): + '''Get the subclass of a class from a specific module.''' + name = class_.__name__ + 'Sub' + if hasattr(module, name): + return getattr(module, name) + else: + return None + + +# +# If you have installed IPython you can uncomment and use the following. +# IPython is available from http://ipython.scipy.org/. +# + +## from IPython.Shell import IPShellEmbed +## args = '' +## ipshell = IPShellEmbed(args, +## banner = 'Dropping into IPython', +## exit_msg = 'Leaving Interpreter, back to program.') + +# Then use the following line where and when you want to drop into the +# IPython shell: +# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') + +# +# Globals +# + +ExternalEncoding = '' +# Set this to false in order to deactivate during export, the use of +# name space prefixes captured from the input document. +UseCapturedNS_ = True +CapturedNsmap_ = {} +Tag_pattern_ = re_.compile(r'({.*})?(.*)') +String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") +Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') +CDATA_pattern_ = re_.compile(r"", re_.DOTALL) + +# Change this to redirect the generated superclass module to use a +# specific subclass module. +CurrentSubclassModule_ = None + +# +# Support/utility functions. +# + + +def showIndent(outfile, level, pretty_print=True): + if pretty_print: + for idx in range(level): + outfile.write(' ') + + +def quote_xml(inStr): + "Escape markup chars, but do not modify CDATA sections." + if not inStr: + return '' + s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) + s2 = '' + pos = 0 + matchobjects = CDATA_pattern_.finditer(s1) + for mo in matchobjects: + s3 = s1[pos:mo.start()] + s2 += quote_xml_aux(s3) + s2 += s1[mo.start():mo.end()] + pos = mo.end() + s3 = s1[pos:] + s2 += quote_xml_aux(s3) + return s2 + + +def quote_xml_aux(inStr): + s1 = inStr.replace('&', '&') + s1 = s1.replace('<', '<') + s1 = s1.replace('>', '>') + return s1 + + +def quote_attrib(inStr): + s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) + s1 = s1.replace('&', '&') + s1 = s1.replace('<', '<') + s1 = s1.replace('>', '>') + s1 = s1.replace('\n', ' ') + if '"' in s1: + if "'" in s1: + s1 = '"%s"' % s1.replace('"', """) + else: + s1 = "'%s'" % s1 + else: + s1 = '"%s"' % s1 + return s1 + + +def quote_python(inStr): + s1 = inStr + if s1.find("'") == -1: + if s1.find('\n') == -1: + return "'%s'" % s1 + else: + return "'''%s'''" % s1 + else: + if s1.find('"') != -1: + s1 = s1.replace('"', '\\"') + if s1.find('\n') == -1: + return '"%s"' % s1 + else: + return '"""%s"""' % s1 + + +def get_all_text_(node): + if node.text is not None: + text = node.text + else: + text = '' + for child in node: + if child.tail is not None: + text += child.tail + return text + + +def find_attr_value_(attr_name, node): + attrs = node.attrib + attr_parts = attr_name.split(':') + value = None + if len(attr_parts) == 1: + value = attrs.get(attr_name) + elif len(attr_parts) == 2: + prefix, name = attr_parts + if prefix == 'xml': + namespace = 'http://www.w3.org/XML/1998/namespace' + else: + namespace = node.nsmap.get(prefix) + if namespace is not None: + value = attrs.get('{%s}%s' % (namespace, name, )) + return value + + +def encode_str_2_3(instr): + return instr + + +class GDSParseError(Exception): + pass + + +def raise_parse_error(node, msg): + if node is not None: + msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) + raise GDSParseError(msg) + + +class MixedContainer: + # Constants for category: + CategoryNone = 0 + CategoryText = 1 + CategorySimple = 2 + CategoryComplex = 3 + # Constants for content_type: + TypeNone = 0 + TypeText = 1 + TypeString = 2 + TypeInteger = 3 + TypeFloat = 4 + TypeDecimal = 5 + TypeDouble = 6 + TypeBoolean = 7 + TypeBase64 = 8 + def __init__(self, category, content_type, name, value): + self.category = category + self.content_type = content_type + self.name = name + self.value = value + def getCategory(self): + return self.category + def getContenttype(self, content_type): + return self.content_type + def getValue(self): + return self.value + def getName(self): + return self.name + def export(self, outfile, level, name, namespace, + pretty_print=True): + if self.category == MixedContainer.CategoryText: + # Prevent exporting empty content as empty lines. + if self.value.strip(): + outfile.write(self.value) + elif self.category == MixedContainer.CategorySimple: + self.exportSimple(outfile, level, name) + else: # category == MixedContainer.CategoryComplex + self.value.export( + outfile, level, namespace, name_=name, + pretty_print=pretty_print) + def exportSimple(self, outfile, level, name): + if self.content_type == MixedContainer.TypeString: + outfile.write('<%s>%s' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeInteger or \ + self.content_type == MixedContainer.TypeBoolean: + outfile.write('<%s>%d' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeFloat or \ + self.content_type == MixedContainer.TypeDecimal: + outfile.write('<%s>%f' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeDouble: + outfile.write('<%s>%g' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeBase64: + outfile.write('<%s>%s' % ( + self.name, + base64.b64encode(self.value), + self.name)) + def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): + if self.category == MixedContainer.CategoryText: + # Prevent exporting empty content as empty lines. + if self.value.strip(): + if len(element) > 0: + if element[-1].tail is None: + element[-1].tail = self.value + else: + element[-1].tail += self.value + else: + if element.text is None: + element.text = self.value + else: + element.text += self.value + elif self.category == MixedContainer.CategorySimple: + subelement = etree_.SubElement( + element, '%s' % self.name) + subelement.text = self.to_etree_simple() + else: # category == MixedContainer.CategoryComplex + self.value.to_etree(element) + def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): + if self.content_type == MixedContainer.TypeString: + text = self.value + elif (self.content_type == MixedContainer.TypeInteger or + self.content_type == MixedContainer.TypeBoolean): + text = '%d' % self.value + elif (self.content_type == MixedContainer.TypeFloat or + self.content_type == MixedContainer.TypeDecimal): + text = '%f' % self.value + elif self.content_type == MixedContainer.TypeDouble: + text = '%g' % self.value + elif self.content_type == MixedContainer.TypeBase64: + text = '%s' % base64.b64encode(self.value) + return text + def exportLiteral(self, outfile, level, name): + if self.category == MixedContainer.CategoryText: + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( + self.category, self.content_type, + self.name, self.value)) + elif self.category == MixedContainer.CategorySimple: + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( + self.category, self.content_type, + self.name, self.value)) + else: # category == MixedContainer.CategoryComplex + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s",\n' % ( + self.category, self.content_type, self.name,)) + self.value.exportLiteral(outfile, level + 1) + showIndent(outfile, level) + outfile.write(')\n') + + +class MemberSpec_(object): + def __init__(self, name='', data_type='', container=0, + optional=0, child_attrs=None, choice=None): + self.name = name + self.data_type = data_type + self.container = container + self.child_attrs = child_attrs + self.choice = choice + self.optional = optional + def set_name(self, name): self.name = name + def get_name(self): return self.name + def set_data_type(self, data_type): self.data_type = data_type + def get_data_type_chain(self): return self.data_type + def get_data_type(self): + if isinstance(self.data_type, list): + if len(self.data_type) > 0: + return self.data_type[-1] + else: + return 'xs:string' + else: + return self.data_type + def set_container(self, container): self.container = container + def get_container(self): return self.container + def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs + def get_child_attrs(self): return self.child_attrs + def set_choice(self, choice): self.choice = choice + def get_choice(self): return self.choice + def set_optional(self, optional): self.optional = optional + def get_optional(self): return self.optional + + +def _cast(typ, value): + if typ is None or value is None: + return value + return typ(value) + +# +# Data representation classes. +# + + +class NFeLoteEnviarArquivo(GeneratedsSuper): + """InscricaoMunicipal -- Numero da inscrição municipal do contribuinte na Prefeitura de Barueri. + CPFCNPJContrib -- CNPJ/CPF do contribuinte + NomeArquivoRPS -- Nome do Arquivo do contribuinte que está sendo enviado para processamento + ApenasValidaArq -- Flag para indicar se o arquivo deve gerar NFe. Caso deseje apenas validar o arquivo informar true, valor padrã o é false + ArquivoRPSBase64 -- Conteúdo do Arquivo do contribuinte em Base64 + + """ + __hash__ = GeneratedsSuper.__hash__ + member_data_items_ = [ + MemberSpec_('InscricaoMunicipal', 'InscricaoMunicipal', 0, 0, {'name': 'InscricaoMunicipal', 'type': 'NFeLoteEnviarArquivo'}, None), + MemberSpec_('CPFCNPJContrib', 'CPFCNPJContrib', 0, 0, {'name': 'CPFCNPJContrib', 'type': 'NFeLoteEnviarArquivo'}, None), + MemberSpec_('NomeArquivoRPS', 'NomeArquivoRPS', 0, 0, {'name': 'CPFCNPJContrib', 'type': 'NFeLoteEnviarArquivo'}, None), + MemberSpec_('ApenasValidaArq', 'ApenasValidaArq', 0, 0, {'name': 'ApenasValidaArq', 'type': 'NFeLoteEnviarArquivo'}, None), + MemberSpec_('ArquivoRPSBase64', 'ArquivoRPSBase64', 0, 0, {'name': 'CPFCNPJContrib', 'type': 'NFeLoteEnviarArquivo'}, None), + ] + + subclass = None + superclass = None + def __init__(self, InscricaoMunicipal=None, CPFCNPJContrib=None, NomeArquivoRPS=None, ApenasValidaArq=None, ArquivoRPSBase64=None, gds_collector_=None, **kwargs_): + self.gds_collector_ = gds_collector_ + self.gds_elementtree_node_ = None + self.original_tagname_ = None + self.parent_object_ = kwargs_.get('parent_object_') + self.ns_prefix_ = None + self.InscricaoMunicipal = InscricaoMunicipal + self.InscricaoMunicipal_nsprefix_ = None + self.CPFCNPJContrib = CPFCNPJContrib + self.CPFCNPJContrib_nsprefix_ = None + self.NomeArquivoRPS = NomeArquivoRPS + self.NomeArquivoRPS_nsprefix_ = None + self.ApenasValidaArq = ApenasValidaArq + self.ApenasValidaArq_nsprefix_ = None + self.ArquivoRPSBase64 = ArquivoRPSBase64 + self.ArquivoRPSBase64_nsprefix_ = None + def factory(*args_, **kwargs_): + if CurrentSubclassModule_ is not None: + subclass = getSubclassFromModule_( + CurrentSubclassModule_, NFeLoteEnviarArquivo) + if subclass is not None: + return subclass(*args_, **kwargs_) + if NFeLoteEnviarArquivo.subclass: + return NFeLoteEnviarArquivo.subclass(*args_, **kwargs_) + else: + return NFeLoteEnviarArquivo(*args_, **kwargs_) + factory = staticmethod(factory) + def get_ns_prefix_(self): + return self.ns_prefix_ + def set_ns_prefix_(self, ns_prefix): + self.ns_prefix_ = ns_prefix + def get_InscricaoMunicipal(self): + return self.InscricaoMunicipal + def set_InscricaoMunicipal(self, InscricaoMunicipal): + self.InscricaoMunicipal = InscricaoMunicipal + def get_CPFCNPJContrib(self): + return self.CPFCNPJContrib + def set_CPFCNPJContrib(self, CPFCNPJContrib): + self.CPFCNPJContrib = CPFCNPJContrib + def get_NomeArquivoRPS(self): + return self.NomeArquivoRPS + def set_NomeArquivoRPS(self, NomeArquivoRPS): + self.NomeArquivoRPS = NomeArquivoRPS + def get_ApenasValidaArq(self): + return self.ApenasValidaArq + def set_ApenasValidaArq(self, ApenasValidaArq): + self.ApenasValidaArq = ApenasValidaArq + def get_ArquivoRPSBase64(self): + return self.ArquivoRPSBase64 + def set_ArquivoRPSBase64(self, ArquivoRPSBase64): + self.ArquivoRPSBase64 = ArquivoRPSBase64 + def _hasContent(self): + if ( + self.InscricaoMunicipal is not None or + self.CPFCNPJContrib is not None or + self.NomeArquivoRPS is not None or + self.ApenasValidaArq is not None or + self.ArquivoRPSBase64 is not None + ): + return True + else: + return False + def export(self, outfile, level, namespaceprefix_='', namespacedef_=' xmlns:None="http://www.barueri.sp.gov.br/nfe" ', name_='NFeLoteEnviarArquivo', pretty_print=True): + imported_ns_def_ = GenerateDSNamespaceDefs_.get('NFeLoteEnviarArquivo') + if imported_ns_def_ is not None: + namespacedef_ = imported_ns_def_ + if pretty_print: + eol_ = '\n' + else: + eol_ = '' + if self.original_tagname_ is not None and name_ == 'NFeLoteEnviarArquivo': + name_ = self.original_tagname_ + if UseCapturedNS_ and self.ns_prefix_: + namespaceprefix_ = self.ns_prefix_ + ':' + showIndent(outfile, level, pretty_print) + outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) + already_processed = set() + self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='NFeLoteEnviarArquivo') + if self._hasContent(): + outfile.write('>%s' % (eol_, )) + self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='NFeLoteEnviarArquivo', pretty_print=pretty_print) + showIndent(outfile, level, pretty_print) + outfile.write('%s' % (namespaceprefix_, name_, eol_)) + else: + outfile.write('/>%s' % (eol_, )) + def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='NFeLoteEnviarArquivo'): + pass + def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_=' xmlns:None="http://www.barueri.sp.gov.br/nfe" ', name_='NFeLoteEnviarArquivo', fromsubclass_=False, pretty_print=True): + if pretty_print: + eol_ = '\n' + else: + eol_ = '' + if self.InscricaoMunicipal is not None: + namespaceprefix_ = self.InscricaoMunicipal_nsprefix_ + ':' if (UseCapturedNS_ and self.InscricaoMunicipal_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sInscricaoMunicipal>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InscricaoMunicipal), input_name='InscricaoMunicipal')), namespaceprefix_ , eol_)) + if self.CPFCNPJContrib is not None: + namespaceprefix_ = self.CPFCNPJContrib_nsprefix_ + ':' if (UseCapturedNS_ and self.CPFCNPJContrib_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sCPFCNPJContrib>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CPFCNPJContrib), input_name='CPFCNPJContrib')), namespaceprefix_ , eol_)) + if self.NomeArquivoRPS is not None: + namespaceprefix_ = self.NomeArquivoRPS_nsprefix_ + ':' if (UseCapturedNS_ and self.NomeArquivoRPS_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sNomeArquivoRPS>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.NomeArquivoRPS), input_name='NomeArquivoRPS')), namespaceprefix_ , eol_)) + if self.ApenasValidaArq is not None: + namespaceprefix_ = self.ApenasValidaArq_nsprefix_ + ':' if (UseCapturedNS_ and self.ApenasValidaArq_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sApenasValidaArq>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.ApenasValidaArq, input_name='ApenasValidaArq'), namespaceprefix_ , eol_)) + if self.ArquivoRPSBase64 is not None: + namespaceprefix_ = self.ArquivoRPSBase64_nsprefix_ + ':' if (UseCapturedNS_ and self.ArquivoRPSBase64_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sArquivoRPSBase64>%s%s' % (namespaceprefix_ , self.gds_format_base64(self.ArquivoRPSBase64, input_name='ArquivoRPSBase64'), namespaceprefix_ , eol_)) + def build(self, node, gds_collector_=None): + self.gds_collector_ = gds_collector_ + if SaveElementTreeNode: + self.gds_elementtree_node_ = node + already_processed = set() + self.ns_prefix_ = node.prefix + self._buildAttributes(node, node.attrib, already_processed) + for child in node: + nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] + self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) + return self + def _buildAttributes(self, node, attrs, already_processed): + pass + def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): + if nodeName_ == 'InscricaoMunicipal': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'InscricaoMunicipal') + value_ = self.gds_validate_string(value_, node, 'InscricaoMunicipal') + self.InscricaoMunicipal = value_ + self.InscricaoMunicipal_nsprefix_ = child_.prefix + elif nodeName_ == 'CPFCNPJContrib': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'CPFCNPJContrib') + value_ = self.gds_validate_string(value_, node, 'CPFCNPJContrib') + self.CPFCNPJContrib = value_ + self.CPFCNPJContrib_nsprefix_ = child_.prefix + elif nodeName_ == 'NomeArquivoRPS': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'NomeArquivoRPS') + value_ = self.gds_validate_string(value_, node, 'NomeArquivoRPS') + self.NomeArquivoRPS = value_ + self.NomeArquivoRPS_nsprefix_ = child_.prefix + elif nodeName_ == 'ApenasValidaArq': + sval_ = child_.text + ival_ = self.gds_parse_boolean(sval_, node, 'ApenasValidaArq') + ival_ = self.gds_validate_boolean(ival_, node, 'ApenasValidaArq') + self.ApenasValidaArq = ival_ + self.ApenasValidaArq_nsprefix_ = child_.prefix + elif nodeName_ == 'ArquivoRPSBase64': + sval_ = child_.text + if sval_ is not None: + try: + bval_ = base64.b64decode(sval_) + except (TypeError, ValueError) as exp: + raise_parse_error(child_, 'requires base64 encoded string: %s' % exp) + bval_ = self.gds_validate_base64(bval_, node, 'ArquivoRPSBase64') + else: + bval_ = None + self.ArquivoRPSBase64 = bval_ + self.ArquivoRPSBase64_nsprefix_ = child_.prefix +# end class NFeLoteEnviarArquivo + + +GDSClassesMapping = { +} + + +USAGE_TEXT = """ +Usage: python .py [ -s ] +""" + + +def usage(): + print(USAGE_TEXT) + sys.exit(1) + + +def get_root_tag(node): + tag = Tag_pattern_.match(node.tag).groups()[-1] + prefix_tag = TagNamePrefix + tag + rootClass = GDSClassesMapping.get(prefix_tag) + if rootClass is None: + rootClass = globals().get(prefix_tag) + return tag, rootClass + + +def get_required_ns_prefix_defs(rootNode): + '''Get all name space prefix definitions required in this XML doc. + Return a dictionary of definitions and a char string of definitions. + ''' + nsmap = { + prefix: uri + for node in rootNode.iter() + for (prefix, uri) in node.nsmap.items() + if prefix is not None + } + namespacedefs = ' '.join([ + 'xmlns:{}="{}"'.format(prefix, uri) + for prefix, uri in nsmap.items() + ]) + return nsmap, namespacedefs + + +def parse(inFileName, silence=False, print_warnings=True): + global CapturedNsmap_ + gds_collector = GdsCollector_() + parser = None + doc = parsexml_(inFileName, parser) + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteEnviarArquivo' + rootClass = NFeLoteEnviarArquivo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + sys.stdout.write('\n') + rootObj.export( + sys.stdout, 0, name_=rootTag, + namespacedef_=namespacedefs, + pretty_print=True) + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def parseEtree(inFileName, silence=False, print_warnings=True, + mapping=None, reverse_mapping=None, nsmap=None): + parser = None + doc = parsexml_(inFileName, parser) + gds_collector = GdsCollector_() + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteEnviarArquivo' + rootClass = NFeLoteEnviarArquivo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + if mapping is None: + mapping = {} + if reverse_mapping is None: + reverse_mapping = {} + rootElement = rootObj.to_etree( + None, name_=rootTag, mapping_=mapping, + reverse_mapping_=reverse_mapping, nsmap_=nsmap) + reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) + # Enable Python to collect the space used by the DOM. + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + content = etree_.tostring( + rootElement, pretty_print=True, + xml_declaration=True, encoding="utf-8") + sys.stdout.write(str(content)) + sys.stdout.write('\n') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj, rootElement, mapping, reverse_node_mapping + + +def parseString(inString, silence=False, print_warnings=True): + '''Parse a string, create the object tree, and export it. + + Arguments: + - inString -- A string. This XML fragment should not start + with an XML declaration containing an encoding. + - silence -- A boolean. If False, export the object. + Returns -- The root object in the tree. + ''' + parser = None + rootNode= parsexmlstring_(inString, parser) + gds_collector = GdsCollector_() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteEnviarArquivo' + rootClass = NFeLoteEnviarArquivo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + if not SaveElementTreeNode: + rootNode = None + if not silence: + sys.stdout.write('\n') + rootObj.export( + sys.stdout, 0, name_=rootTag, + namespacedef_='') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def parseLiteral(inFileName, silence=False, print_warnings=True): + parser = None + doc = parsexml_(inFileName, parser) + gds_collector = GdsCollector_() + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteEnviarArquivo' + rootClass = NFeLoteEnviarArquivo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + # Enable Python to collect the space used by the DOM. + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + sys.stdout.write('#from NFeLoteEnviarArquivo import *\n\n') + sys.stdout.write('import NFeLoteEnviarArquivo as model_\n\n') + sys.stdout.write('rootObj = model_.rootClass(\n') + rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) + sys.stdout.write(')\n') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def main(): + args = sys.argv[1:] + if len(args) == 1: + parse(args[0]) + else: + usage() + + +if __name__ == '__main__': + #import pdb; pdb.set_trace() + main() + +RenameMappings_ = { +} + +# +# Mapping of namespaces to types defined in them +# and the file in which each is defined. +# simpleTypes are marked "ST" and complexTypes "CT". +NamespaceToDefMappings_ = {'http://www.barueri.sp.gov.br/nfe': [ + ( + 'InscricaoMunicipal', + 'NFeLoteEnviarArquivo.v1.xsd', + 'ST' + ), + ( + 'CPFCNPJContrib', + 'NFeLoteEnviarArquivo.v1.xsd', + 'ST' + ), + ( + 'NomeArquivoRPS', + 'NFeLoteEnviarArquivo.v1.xsd', + 'ST' + ), + ( + 'ApenasValidaArq', + 'NFeLoteEnviarArquivo.v1.xsd', + 'ST' + ), + ( + 'ArquivoRPSBase64', + 'NFeLoteEnviarArquivo.v1.xsd', + 'ST' + ) + ], +} + +__all__ = [ + "NFeLoteEnviarArquivo" +] diff --git a/nfselib/barueri/NFeLoteListarArquivo.py b/nfselib/barueri/NFeLoteListarArquivo.py new file mode 100644 index 0000000..96a8421 --- /dev/null +++ b/nfselib/barueri/NFeLoteListarArquivo.py @@ -0,0 +1,1396 @@ +#TODO + +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# +# Generated Thu Apr 13 03:37:13 2023 by generateDS.py version 2.41.3. +# Python 3.8.10 (default, Mar 13 2023, 10:26:41) [GCC 9.4.0] +# +# Command line options: +# ('-o', 'NFeLoteListarArquivo.py') +# +# Command line arguments: +# ../../schemas/barueri/NFeLoteListarArquivos.v1.xsd +# +# Command line: +# /home/andre/.local/bin/generateDS -o "NFeLoteListarArquivo.py" ../../schemas/barueri/NFeLoteListarArquivos.v1.xsd +# +# Current working directory (os.getcwd()): +# barueri +# + +import sys +try: + ModulenotfoundExp_ = ModuleNotFoundError +except NameError: + ModulenotfoundExp_ = ImportError +from six.moves import zip_longest +import os +import re as re_ +import base64 +import datetime as datetime_ +import decimal as decimal_ +from lxml import etree as etree_ + + +Validate_simpletypes_ = True +SaveElementTreeNode = True +TagNamePrefix = "" +if sys.version_info.major == 2: + BaseStrType_ = basestring +else: + BaseStrType_ = str + + +def parsexml_(infile, parser=None, **kwargs): + if parser is None: + # Use the lxml ElementTree compatible parser so that, e.g., + # we ignore comments. + try: + parser = etree_.ETCompatXMLParser() + except AttributeError: + # fallback to xml.etree + parser = etree_.XMLParser() + try: + if isinstance(infile, os.PathLike): + infile = os.path.join(infile) + except AttributeError: + pass + doc = etree_.parse(infile, parser=parser, **kwargs) + return doc + +def parsexmlstring_(instring, parser=None, **kwargs): + if parser is None: + # Use the lxml ElementTree compatible parser so that, e.g., + # we ignore comments. + try: + parser = etree_.ETCompatXMLParser() + except AttributeError: + # fallback to xml.etree + parser = etree_.XMLParser() + element = etree_.fromstring(instring, parser=parser, **kwargs) + return element + +# +# Namespace prefix definition table (and other attributes, too) +# +# The module generatedsnamespaces, if it is importable, must contain +# a dictionary named GeneratedsNamespaceDefs. This Python dictionary +# should map element type names (strings) to XML schema namespace prefix +# definitions. The export method for any class for which there is +# a namespace prefix definition, will export that definition in the +# XML representation of that element. See the export method of +# any generated element type class for an example of the use of this +# table. +# A sample table is: +# +# # File: generatedsnamespaces.py +# +# GenerateDSNamespaceDefs = { +# "ElementtypeA": "http://www.xxx.com/namespaceA", +# "ElementtypeB": "http://www.xxx.com/namespaceB", +# } +# +# Additionally, the generatedsnamespaces module can contain a python +# dictionary named GenerateDSNamespaceTypePrefixes that associates element +# types with the namespace prefixes that are to be added to the +# "xsi:type" attribute value. See the _exportAttributes method of +# any generated element type and the generation of "xsi:type" for an +# example of the use of this table. +# An example table: +# +# # File: generatedsnamespaces.py +# +# GenerateDSNamespaceTypePrefixes = { +# "ElementtypeC": "aaa:", +# "ElementtypeD": "bbb:", +# } +# + +try: + from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ +except ModulenotfoundExp_ : + GenerateDSNamespaceDefs_ = {} +try: + from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ +except ModulenotfoundExp_ : + GenerateDSNamespaceTypePrefixes_ = {} + +# +# You can replace the following class definition by defining an +# importable module named "generatedscollector" containing a class +# named "GdsCollector". See the default class definition below for +# clues about the possible content of that class. +# +try: + from generatedscollector import GdsCollector as GdsCollector_ +except ModulenotfoundExp_ : + + class GdsCollector_(object): + + def __init__(self, messages=None): + if messages is None: + self.messages = [] + else: + self.messages = messages + + def add_message(self, msg): + self.messages.append(msg) + + def get_messages(self): + return self.messages + + def clear_messages(self): + self.messages = [] + + def print_messages(self): + for msg in self.messages: + print("Warning: {}".format(msg)) + + def write_messages(self, outstream): + for msg in self.messages: + outstream.write("Warning: {}\n".format(msg)) + + +# +# The super-class for enum types +# + +try: + from enum import Enum +except ModulenotfoundExp_ : + Enum = object + +# +# The root super-class for element type classes +# +# Calls to the methods in these classes are generated by generateDS.py. +# You can replace these methods by re-implementing the following class +# in a module named generatedssuper.py. + +try: + from generatedssuper import GeneratedsSuper +except ModulenotfoundExp_ as exp: + try: + from generatedssupersuper import GeneratedsSuperSuper + except ModulenotfoundExp_ as exp: + class GeneratedsSuperSuper(object): + pass + + class GeneratedsSuper(GeneratedsSuperSuper): + __hash__ = object.__hash__ + tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') + class _FixedOffsetTZ(datetime_.tzinfo): + def __init__(self, offset, name): + self.__offset = datetime_.timedelta(minutes=offset) + self.__name = name + def utcoffset(self, dt): + return self.__offset + def tzname(self, dt): + return self.__name + def dst(self, dt): + return None + def __str__(self): + settings = { + 'str_pretty_print': True, + 'str_indent_level': 0, + 'str_namespaceprefix': '', + 'str_name': self.__class__.__name__, + 'str_namespacedefs': '', + } + for n in settings: + if hasattr(self, n): + settings[n] = getattr(self, n) + if sys.version_info.major == 2: + from StringIO import StringIO + else: + from io import StringIO + output = StringIO() + self.export( + output, + settings['str_indent_level'], + pretty_print=settings['str_pretty_print'], + namespaceprefix_=settings['str_namespaceprefix'], + name_=settings['str_name'], + namespacedef_=settings['str_namespacedefs'] + ) + strval = output.getvalue() + output.close() + return strval + def gds_format_string(self, input_data, input_name=''): + return input_data + def gds_parse_string(self, input_data, node=None, input_name=''): + return input_data + def gds_validate_string(self, input_data, node=None, input_name=''): + if not input_data: + return '' + else: + return input_data + def gds_format_base64(self, input_data, input_name=''): + return base64.b64encode(input_data).decode('ascii') + def gds_validate_base64(self, input_data, node=None, input_name=''): + return input_data + def gds_format_integer(self, input_data, input_name=''): + return '%d' % int(input_data) + def gds_parse_integer(self, input_data, node=None, input_name=''): + try: + ival = int(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires integer value: %s' % exp) + return ival + def gds_validate_integer(self, input_data, node=None, input_name=''): + try: + value = int(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires integer value') + return value + def gds_format_integer_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_integer_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + int(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of integer values') + return values + def gds_format_float(self, input_data, input_name=''): + return ('%.15f' % float(input_data)).rstrip('0') + def gds_parse_float(self, input_data, node=None, input_name=''): + try: + fval_ = float(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires float or double value: %s' % exp) + return fval_ + def gds_validate_float(self, input_data, node=None, input_name=''): + try: + value = float(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires float value') + return value + def gds_format_float_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_float_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + float(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of float values') + return values + def gds_format_decimal(self, input_data, input_name=''): + return_value = '%s' % input_data + if '.' in return_value: + return_value = return_value.rstrip('0') + if return_value.endswith('.'): + return_value = return_value.rstrip('.') + return return_value + def gds_parse_decimal(self, input_data, node=None, input_name=''): + try: + decimal_value = decimal_.Decimal(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires decimal value') + return decimal_value + def gds_validate_decimal(self, input_data, node=None, input_name=''): + try: + value = decimal_.Decimal(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires decimal value') + return value + def gds_format_decimal_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return ' '.join([self.gds_format_decimal(item) for item in input_data]) + def gds_validate_decimal_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + decimal_.Decimal(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of decimal values') + return values + def gds_format_double(self, input_data, input_name=''): + return '%s' % input_data + def gds_parse_double(self, input_data, node=None, input_name=''): + try: + fval_ = float(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires double or float value: %s' % exp) + return fval_ + def gds_validate_double(self, input_data, node=None, input_name=''): + try: + value = float(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires double or float value') + return value + def gds_format_double_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_double_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + float(value) + except (TypeError, ValueError): + raise_parse_error( + node, 'Requires sequence of double or float values') + return values + def gds_format_boolean(self, input_data, input_name=''): + return ('%s' % input_data).lower() + def gds_parse_boolean(self, input_data, node=None, input_name=''): + input_data = input_data.strip() + if input_data in ('true', '1'): + bval = True + elif input_data in ('false', '0'): + bval = False + else: + raise_parse_error(node, 'Requires boolean value') + return bval + def gds_validate_boolean(self, input_data, node=None, input_name=''): + if input_data not in (True, 1, False, 0, ): + raise_parse_error( + node, + 'Requires boolean value ' + '(one of True, 1, False, 0)') + return input_data + def gds_format_boolean_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_boolean_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + value = self.gds_parse_boolean(value, node, input_name) + if value not in (True, 1, False, 0, ): + raise_parse_error( + node, + 'Requires sequence of boolean values ' + '(one of True, 1, False, 0)') + return values + def gds_validate_datetime(self, input_data, node=None, input_name=''): + return input_data + def gds_format_datetime(self, input_data, input_name=''): + if input_data.microsecond == 0: + _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( + input_data.year, + input_data.month, + input_data.day, + input_data.hour, + input_data.minute, + input_data.second, + ) + else: + _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( + input_data.year, + input_data.month, + input_data.day, + input_data.hour, + input_data.minute, + input_data.second, + ('%f' % (float(input_data.microsecond) / 1000000))[2:], + ) + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) + return _svalue + @classmethod + def gds_parse_datetime(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + time_parts = input_data.split('.') + if len(time_parts) > 1: + micro_seconds = int(float('0.' + time_parts[1]) * 1000000) + input_data = '%s.%s' % ( + time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) + dt = datetime_.datetime.strptime( + input_data, '%Y-%m-%dT%H:%M:%S.%f') + else: + dt = datetime_.datetime.strptime( + input_data, '%Y-%m-%dT%H:%M:%S') + dt = dt.replace(tzinfo=tz) + return dt + def gds_validate_date(self, input_data, node=None, input_name=''): + return input_data + def gds_format_date(self, input_data, input_name=''): + _svalue = '%04d-%02d-%02d' % ( + input_data.year, + input_data.month, + input_data.day, + ) + try: + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format( + hours, minutes) + except AttributeError: + pass + return _svalue + @classmethod + def gds_parse_date(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') + dt = dt.replace(tzinfo=tz) + return dt.date() + def gds_validate_time(self, input_data, node=None, input_name=''): + return input_data + def gds_format_time(self, input_data, input_name=''): + if input_data.microsecond == 0: + _svalue = '%02d:%02d:%02d' % ( + input_data.hour, + input_data.minute, + input_data.second, + ) + else: + _svalue = '%02d:%02d:%02d.%s' % ( + input_data.hour, + input_data.minute, + input_data.second, + ('%f' % (float(input_data.microsecond) / 1000000))[2:], + ) + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) + return _svalue + def gds_validate_simple_patterns(self, patterns, target): + # pat is a list of lists of strings/patterns. + # The target value must match at least one of the patterns + # in order for the test to succeed. + found1 = True + target = str(target) + for patterns1 in patterns: + found2 = False + for patterns2 in patterns1: + mo = re_.search(patterns2, target) + if mo is not None and len(mo.group(0)) == len(target): + found2 = True + break + if not found2: + found1 = False + break + return found1 + @classmethod + def gds_parse_time(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + if len(input_data.split('.')) > 1: + dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') + else: + dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') + dt = dt.replace(tzinfo=tz) + return dt.time() + def gds_check_cardinality_( + self, value, input_name, + min_occurs=0, max_occurs=1, required=None): + if value is None: + length = 0 + elif isinstance(value, list): + length = len(value) + else: + length = 1 + if required is not None : + if required and length < 1: + self.gds_collector_.add_message( + "Required value {}{} is missing".format( + input_name, self.gds_get_node_lineno_())) + if length < min_occurs: + self.gds_collector_.add_message( + "Number of values for {}{} is below " + "the minimum allowed, " + "expected at least {}, found {}".format( + input_name, self.gds_get_node_lineno_(), + min_occurs, length)) + elif length > max_occurs: + self.gds_collector_.add_message( + "Number of values for {}{} is above " + "the maximum allowed, " + "expected at most {}, found {}".format( + input_name, self.gds_get_node_lineno_(), + max_occurs, length)) + def gds_validate_builtin_ST_( + self, validator, value, input_name, + min_occurs=None, max_occurs=None, required=None): + if value is not None: + try: + validator(value, input_name=input_name) + except GDSParseError as parse_error: + self.gds_collector_.add_message(str(parse_error)) + def gds_validate_defined_ST_( + self, validator, value, input_name, + min_occurs=None, max_occurs=None, required=None): + if value is not None: + try: + validator(value) + except GDSParseError as parse_error: + self.gds_collector_.add_message(str(parse_error)) + def gds_str_lower(self, instring): + return instring.lower() + def get_path_(self, node): + path_list = [] + self.get_path_list_(node, path_list) + path_list.reverse() + path = '/'.join(path_list) + return path + Tag_strip_pattern_ = re_.compile(r'\{.*\}') + def get_path_list_(self, node, path_list): + if node is None: + return + tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) + if tag: + path_list.append(tag) + self.get_path_list_(node.getparent(), path_list) + def get_class_obj_(self, node, default_class=None): + class_obj1 = default_class + if 'xsi' in node.nsmap: + classname = node.get('{%s}type' % node.nsmap['xsi']) + if classname is not None: + names = classname.split(':') + if len(names) == 2: + classname = names[1] + class_obj2 = globals().get(classname) + if class_obj2 is not None: + class_obj1 = class_obj2 + return class_obj1 + def gds_build_any(self, node, type_name=None): + # provide default value in case option --disable-xml is used. + content = "" + content = etree_.tostring(node, encoding="unicode") + return content + @classmethod + def gds_reverse_node_mapping(cls, mapping): + return dict(((v, k) for k, v in mapping.items())) + @staticmethod + def gds_encode(instring): + if sys.version_info.major == 2: + if ExternalEncoding: + encoding = ExternalEncoding + else: + encoding = 'utf-8' + return instring.encode(encoding) + else: + return instring + @staticmethod + def convert_unicode(instring): + if isinstance(instring, str): + result = quote_xml(instring) + elif sys.version_info.major == 2 and isinstance(instring, unicode): + result = quote_xml(instring).encode('utf8') + else: + result = GeneratedsSuper.gds_encode(str(instring)) + return result + def __eq__(self, other): + def excl_select_objs_(obj): + return (obj[0] != 'parent_object_' and + obj[0] != 'gds_collector_') + if type(self) != type(other): + return False + return all(x == y for x, y in zip_longest( + filter(excl_select_objs_, self.__dict__.items()), + filter(excl_select_objs_, other.__dict__.items()))) + def __ne__(self, other): + return not self.__eq__(other) + # Django ETL transform hooks. + def gds_djo_etl_transform(self): + pass + def gds_djo_etl_transform_db_obj(self, dbobj): + pass + # SQLAlchemy ETL transform hooks. + def gds_sqa_etl_transform(self): + return 0, None + def gds_sqa_etl_transform_db_obj(self, dbobj): + pass + def gds_get_node_lineno_(self): + if (hasattr(self, "gds_elementtree_node_") and + self.gds_elementtree_node_ is not None): + return ' near line {}'.format( + self.gds_elementtree_node_.sourceline) + else: + return "" + + + def getSubclassFromModule_(module, class_): + '''Get the subclass of a class from a specific module.''' + name = class_.__name__ + 'Sub' + if hasattr(module, name): + return getattr(module, name) + else: + return None + + +# +# If you have installed IPython you can uncomment and use the following. +# IPython is available from http://ipython.scipy.org/. +# + +## from IPython.Shell import IPShellEmbed +## args = '' +## ipshell = IPShellEmbed(args, +## banner = 'Dropping into IPython', +## exit_msg = 'Leaving Interpreter, back to program.') + +# Then use the following line where and when you want to drop into the +# IPython shell: +# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') + +# +# Globals +# + +ExternalEncoding = '' +# Set this to false in order to deactivate during export, the use of +# name space prefixes captured from the input document. +UseCapturedNS_ = True +CapturedNsmap_ = {} +Tag_pattern_ = re_.compile(r'({.*})?(.*)') +String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") +Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') +CDATA_pattern_ = re_.compile(r"", re_.DOTALL) + +# Change this to redirect the generated superclass module to use a +# specific subclass module. +CurrentSubclassModule_ = None + +# +# Support/utility functions. +# + + +def showIndent(outfile, level, pretty_print=True): + if pretty_print: + for idx in range(level): + outfile.write(' ') + + +def quote_xml(inStr): + "Escape markup chars, but do not modify CDATA sections." + if not inStr: + return '' + s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) + s2 = '' + pos = 0 + matchobjects = CDATA_pattern_.finditer(s1) + for mo in matchobjects: + s3 = s1[pos:mo.start()] + s2 += quote_xml_aux(s3) + s2 += s1[mo.start():mo.end()] + pos = mo.end() + s3 = s1[pos:] + s2 += quote_xml_aux(s3) + return s2 + + +def quote_xml_aux(inStr): + s1 = inStr.replace('&', '&') + s1 = s1.replace('<', '<') + s1 = s1.replace('>', '>') + return s1 + + +def quote_attrib(inStr): + s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) + s1 = s1.replace('&', '&') + s1 = s1.replace('<', '<') + s1 = s1.replace('>', '>') + s1 = s1.replace('\n', ' ') + if '"' in s1: + if "'" in s1: + s1 = '"%s"' % s1.replace('"', """) + else: + s1 = "'%s'" % s1 + else: + s1 = '"%s"' % s1 + return s1 + + +def quote_python(inStr): + s1 = inStr + if s1.find("'") == -1: + if s1.find('\n') == -1: + return "'%s'" % s1 + else: + return "'''%s'''" % s1 + else: + if s1.find('"') != -1: + s1 = s1.replace('"', '\\"') + if s1.find('\n') == -1: + return '"%s"' % s1 + else: + return '"""%s"""' % s1 + + +def get_all_text_(node): + if node.text is not None: + text = node.text + else: + text = '' + for child in node: + if child.tail is not None: + text += child.tail + return text + + +def find_attr_value_(attr_name, node): + attrs = node.attrib + attr_parts = attr_name.split(':') + value = None + if len(attr_parts) == 1: + value = attrs.get(attr_name) + elif len(attr_parts) == 2: + prefix, name = attr_parts + if prefix == 'xml': + namespace = 'http://www.w3.org/XML/1998/namespace' + else: + namespace = node.nsmap.get(prefix) + if namespace is not None: + value = attrs.get('{%s}%s' % (namespace, name, )) + return value + + +def encode_str_2_3(instr): + return instr + + +class GDSParseError(Exception): + pass + + +def raise_parse_error(node, msg): + if node is not None: + msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) + raise GDSParseError(msg) + + +class MixedContainer: + # Constants for category: + CategoryNone = 0 + CategoryText = 1 + CategorySimple = 2 + CategoryComplex = 3 + # Constants for content_type: + TypeNone = 0 + TypeText = 1 + TypeString = 2 + TypeInteger = 3 + TypeFloat = 4 + TypeDecimal = 5 + TypeDouble = 6 + TypeBoolean = 7 + TypeBase64 = 8 + def __init__(self, category, content_type, name, value): + self.category = category + self.content_type = content_type + self.name = name + self.value = value + def getCategory(self): + return self.category + def getContenttype(self, content_type): + return self.content_type + def getValue(self): + return self.value + def getName(self): + return self.name + def export(self, outfile, level, name, namespace, + pretty_print=True): + if self.category == MixedContainer.CategoryText: + # Prevent exporting empty content as empty lines. + if self.value.strip(): + outfile.write(self.value) + elif self.category == MixedContainer.CategorySimple: + self.exportSimple(outfile, level, name) + else: # category == MixedContainer.CategoryComplex + self.value.export( + outfile, level, namespace, name_=name, + pretty_print=pretty_print) + def exportSimple(self, outfile, level, name): + if self.content_type == MixedContainer.TypeString: + outfile.write('<%s>%s' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeInteger or \ + self.content_type == MixedContainer.TypeBoolean: + outfile.write('<%s>%d' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeFloat or \ + self.content_type == MixedContainer.TypeDecimal: + outfile.write('<%s>%f' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeDouble: + outfile.write('<%s>%g' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeBase64: + outfile.write('<%s>%s' % ( + self.name, + base64.b64encode(self.value), + self.name)) + def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): + if self.category == MixedContainer.CategoryText: + # Prevent exporting empty content as empty lines. + if self.value.strip(): + if len(element) > 0: + if element[-1].tail is None: + element[-1].tail = self.value + else: + element[-1].tail += self.value + else: + if element.text is None: + element.text = self.value + else: + element.text += self.value + elif self.category == MixedContainer.CategorySimple: + subelement = etree_.SubElement( + element, '%s' % self.name) + subelement.text = self.to_etree_simple() + else: # category == MixedContainer.CategoryComplex + self.value.to_etree(element) + def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): + if self.content_type == MixedContainer.TypeString: + text = self.value + elif (self.content_type == MixedContainer.TypeInteger or + self.content_type == MixedContainer.TypeBoolean): + text = '%d' % self.value + elif (self.content_type == MixedContainer.TypeFloat or + self.content_type == MixedContainer.TypeDecimal): + text = '%f' % self.value + elif self.content_type == MixedContainer.TypeDouble: + text = '%g' % self.value + elif self.content_type == MixedContainer.TypeBase64: + text = '%s' % base64.b64encode(self.value) + return text + def exportLiteral(self, outfile, level, name): + if self.category == MixedContainer.CategoryText: + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( + self.category, self.content_type, + self.name, self.value)) + elif self.category == MixedContainer.CategorySimple: + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( + self.category, self.content_type, + self.name, self.value)) + else: # category == MixedContainer.CategoryComplex + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s",\n' % ( + self.category, self.content_type, self.name,)) + self.value.exportLiteral(outfile, level + 1) + showIndent(outfile, level) + outfile.write(')\n') + + +class MemberSpec_(object): + def __init__(self, name='', data_type='', container=0, + optional=0, child_attrs=None, choice=None): + self.name = name + self.data_type = data_type + self.container = container + self.child_attrs = child_attrs + self.choice = choice + self.optional = optional + def set_name(self, name): self.name = name + def get_name(self): return self.name + def set_data_type(self, data_type): self.data_type = data_type + def get_data_type_chain(self): return self.data_type + def get_data_type(self): + if isinstance(self.data_type, list): + if len(self.data_type) > 0: + return self.data_type[-1] + else: + return 'xs:string' + else: + return self.data_type + def set_container(self, container): self.container = container + def get_container(self): return self.container + def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs + def get_child_attrs(self): return self.child_attrs + def set_choice(self, choice): self.choice = choice + def get_choice(self): return self.choice + def set_optional(self, optional): self.optional = optional + def get_optional(self): return self.optional + + +def _cast(typ, value): + if typ is None or value is None: + return value + return typ(value) + +# +# Data representation classes. +# + + +class tsSitucaoArquivoRPS(str, Enum): + TODAS='TODAS' + _2='-2' + _1='-1' + _0='0' + _1_1='1' + _2_1='2' + + +class NFeLoteListarArquivos(GeneratedsSuper): + """InscricaoMunicipal -- Numero da inscri + ç + ã + o municipal do contribuinte na Prefeitura de Barueri. + CPFCNPJContrib -- CNPJ/CPF do Prestador do contribuinte + DataEnvioArq -- Data de envio dos arquivos de remessa ao sistema NFe (AAAA-MM-DD). + SituacaoArq -- Indicar a situa + ç + ã + o dos arquivos + + """ + __hash__ = GeneratedsSuper.__hash__ + subclass = None + superclass = None + def __init__(self, InscricaoMunicipal=None, CPFCNPJContrib=None, DataEnvioArq=None, SituacaoArq=None, gds_collector_=None, **kwargs_): + self.gds_collector_ = gds_collector_ + self.gds_elementtree_node_ = None + self.original_tagname_ = None + self.parent_object_ = kwargs_.get('parent_object_') + self.ns_prefix_ = None + self.InscricaoMunicipal = InscricaoMunicipal + self.InscricaoMunicipal_nsprefix_ = None + self.CPFCNPJContrib = CPFCNPJContrib + self.CPFCNPJContrib_nsprefix_ = None + if isinstance(DataEnvioArq, BaseStrType_): + initvalue_ = datetime_.datetime.strptime(DataEnvioArq, '%Y-%m-%d').date() + else: + initvalue_ = DataEnvioArq + self.DataEnvioArq = initvalue_ + self.DataEnvioArq_nsprefix_ = None + self.SituacaoArq = SituacaoArq + self.validate_tsSitucaoArquivoRPS(self.SituacaoArq) + self.SituacaoArq_nsprefix_ = None + def factory(*args_, **kwargs_): + if CurrentSubclassModule_ is not None: + subclass = getSubclassFromModule_( + CurrentSubclassModule_, NFeLoteListarArquivos) + if subclass is not None: + return subclass(*args_, **kwargs_) + if NFeLoteListarArquivos.subclass: + return NFeLoteListarArquivos.subclass(*args_, **kwargs_) + else: + return NFeLoteListarArquivos(*args_, **kwargs_) + factory = staticmethod(factory) + def get_ns_prefix_(self): + return self.ns_prefix_ + def set_ns_prefix_(self, ns_prefix): + self.ns_prefix_ = ns_prefix + def get_InscricaoMunicipal(self): + return self.InscricaoMunicipal + def set_InscricaoMunicipal(self, InscricaoMunicipal): + self.InscricaoMunicipal = InscricaoMunicipal + def get_CPFCNPJContrib(self): + return self.CPFCNPJContrib + def set_CPFCNPJContrib(self, CPFCNPJContrib): + self.CPFCNPJContrib = CPFCNPJContrib + def get_DataEnvioArq(self): + return self.DataEnvioArq + def set_DataEnvioArq(self, DataEnvioArq): + self.DataEnvioArq = DataEnvioArq + def get_SituacaoArq(self): + return self.SituacaoArq + def set_SituacaoArq(self, SituacaoArq): + self.SituacaoArq = SituacaoArq + def validate_tsSitucaoArquivoRPS(self, value): + result = True + # Validate type tsSitucaoArquivoRPS, a restriction on xs:string. + if value is not None and Validate_simpletypes_ and self.gds_collector_ is not None: + if not isinstance(value, str): + lineno = self.gds_get_node_lineno_() + self.gds_collector_.add_message('Value "%(value)s"%(lineno)s is not of the correct base simple type (str)' % {"value": value, "lineno": lineno, }) + return False + value = value + enumerations = ['TODAS', '-2', '-1', '0', '1', '2'] + if value not in enumerations: + lineno = self.gds_get_node_lineno_() + self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd enumeration restriction on tsSitucaoArquivoRPS' % {"value" : encode_str_2_3(value), "lineno": lineno} ) + result = False + return result + def _hasContent(self): + if ( + self.InscricaoMunicipal is not None or + self.CPFCNPJContrib is not None or + self.DataEnvioArq is not None or + self.SituacaoArq is not None + ): + return True + else: + return False + def export(self, outfile, level, namespaceprefix_='', namespacedef_='xmlns:NS="http://www.barueri.sp.gov.br/nfe" xmlns:None="http://www.barueri.sp.gov.br/nfe" ', name_='NFeLoteListarArquivos', pretty_print=True): + imported_ns_def_ = GenerateDSNamespaceDefs_.get('NFeLoteListarArquivos') + if imported_ns_def_ is not None: + namespacedef_ = imported_ns_def_ + if pretty_print: + eol_ = '\n' + else: + eol_ = '' + if self.original_tagname_ is not None and name_ == 'NFeLoteListarArquivos': + name_ = self.original_tagname_ + if UseCapturedNS_ and self.ns_prefix_: + namespaceprefix_ = self.ns_prefix_ + ':' + showIndent(outfile, level, pretty_print) + outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) + already_processed = set() + self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='NFeLoteListarArquivos') + if self._hasContent(): + outfile.write('>%s' % (eol_, )) + self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='NFeLoteListarArquivos', pretty_print=pretty_print) + showIndent(outfile, level, pretty_print) + outfile.write('%s' % (namespaceprefix_, name_, eol_)) + else: + outfile.write('/>%s' % (eol_, )) + def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='NFeLoteListarArquivos'): + pass + def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='xmlns:NS="http://www.barueri.sp.gov.br/nfe" xmlns:None="http://www.barueri.sp.gov.br/nfe" ', name_='NFeLoteListarArquivos', fromsubclass_=False, pretty_print=True): + if pretty_print: + eol_ = '\n' + else: + eol_ = '' + if self.InscricaoMunicipal is not None: + namespaceprefix_ = self.InscricaoMunicipal_nsprefix_ + ':' if (UseCapturedNS_ and self.InscricaoMunicipal_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sInscricaoMunicipal>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InscricaoMunicipal), input_name='InscricaoMunicipal')), namespaceprefix_ , eol_)) + if self.CPFCNPJContrib is not None: + namespaceprefix_ = self.CPFCNPJContrib_nsprefix_ + ':' if (UseCapturedNS_ and self.CPFCNPJContrib_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sCPFCNPJContrib>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CPFCNPJContrib), input_name='CPFCNPJContrib')), namespaceprefix_ , eol_)) + if self.DataEnvioArq is not None: + namespaceprefix_ = self.DataEnvioArq_nsprefix_ + ':' if (UseCapturedNS_ and self.DataEnvioArq_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sDataEnvioArq>%s%s' % (namespaceprefix_ , self.gds_format_date(self.DataEnvioArq, input_name='DataEnvioArq'), namespaceprefix_ , eol_)) + if self.SituacaoArq is not None: + namespaceprefix_ = self.SituacaoArq_nsprefix_ + ':' if (UseCapturedNS_ and self.SituacaoArq_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sSituacaoArq>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SituacaoArq), input_name='SituacaoArq')), namespaceprefix_ , eol_)) + def build(self, node, gds_collector_=None): + self.gds_collector_ = gds_collector_ + if SaveElementTreeNode: + self.gds_elementtree_node_ = node + already_processed = set() + self.ns_prefix_ = node.prefix + self._buildAttributes(node, node.attrib, already_processed) + for child in node: + nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] + self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) + return self + def _buildAttributes(self, node, attrs, already_processed): + pass + def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): + if nodeName_ == 'InscricaoMunicipal': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'InscricaoMunicipal') + value_ = self.gds_validate_string(value_, node, 'InscricaoMunicipal') + self.InscricaoMunicipal = value_ + self.InscricaoMunicipal_nsprefix_ = child_.prefix + elif nodeName_ == 'CPFCNPJContrib': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'CPFCNPJContrib') + value_ = self.gds_validate_string(value_, node, 'CPFCNPJContrib') + self.CPFCNPJContrib = value_ + self.CPFCNPJContrib_nsprefix_ = child_.prefix + elif nodeName_ == 'DataEnvioArq': + sval_ = child_.text + dval_ = self.gds_parse_date(sval_) + self.DataEnvioArq = dval_ + self.DataEnvioArq_nsprefix_ = child_.prefix + elif nodeName_ == 'SituacaoArq': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'SituacaoArq') + value_ = self.gds_validate_string(value_, node, 'SituacaoArq') + self.SituacaoArq = value_ + self.SituacaoArq_nsprefix_ = child_.prefix + # validate type tsSitucaoArquivoRPS + self.validate_tsSitucaoArquivoRPS(self.SituacaoArq) +# end class NFeLoteListarArquivos + + +GDSClassesMapping = { +} + + +USAGE_TEXT = """ +Usage: python .py [ -s ] +""" + + +def usage(): + print(USAGE_TEXT) + sys.exit(1) + + +def get_root_tag(node): + tag = Tag_pattern_.match(node.tag).groups()[-1] + prefix_tag = TagNamePrefix + tag + rootClass = GDSClassesMapping.get(prefix_tag) + if rootClass is None: + rootClass = globals().get(prefix_tag) + return tag, rootClass + + +def get_required_ns_prefix_defs(rootNode): + '''Get all name space prefix definitions required in this XML doc. + Return a dictionary of definitions and a char string of definitions. + ''' + nsmap = { + prefix: uri + for node in rootNode.iter() + for (prefix, uri) in node.nsmap.items() + if prefix is not None + } + namespacedefs = ' '.join([ + 'xmlns:{}="{}"'.format(prefix, uri) + for prefix, uri in nsmap.items() + ]) + return nsmap, namespacedefs + + +def parse(inFileName, silence=False, print_warnings=True): + global CapturedNsmap_ + gds_collector = GdsCollector_() + parser = None + doc = parsexml_(inFileName, parser) + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteListarArquivos' + rootClass = NFeLoteListarArquivos + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + sys.stdout.write('\n') + rootObj.export( + sys.stdout, 0, name_=rootTag, + namespacedef_=namespacedefs, + pretty_print=True) + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def parseEtree(inFileName, silence=False, print_warnings=True, + mapping=None, reverse_mapping=None, nsmap=None): + parser = None + doc = parsexml_(inFileName, parser) + gds_collector = GdsCollector_() + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteListarArquivos' + rootClass = NFeLoteListarArquivos + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + if mapping is None: + mapping = {} + if reverse_mapping is None: + reverse_mapping = {} + rootElement = rootObj.to_etree( + None, name_=rootTag, mapping_=mapping, + reverse_mapping_=reverse_mapping, nsmap_=nsmap) + reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) + # Enable Python to collect the space used by the DOM. + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + content = etree_.tostring( + rootElement, pretty_print=True, + xml_declaration=True, encoding="utf-8") + sys.stdout.write(str(content)) + sys.stdout.write('\n') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj, rootElement, mapping, reverse_node_mapping + + +def parseString(inString, silence=False, print_warnings=True): + '''Parse a string, create the object tree, and export it. + + Arguments: + - inString -- A string. This XML fragment should not start + with an XML declaration containing an encoding. + - silence -- A boolean. If False, export the object. + Returns -- The root object in the tree. + ''' + parser = None + rootNode= parsexmlstring_(inString, parser) + gds_collector = GdsCollector_() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteListarArquivos' + rootClass = NFeLoteListarArquivos + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + if not SaveElementTreeNode: + rootNode = None + if not silence: + sys.stdout.write('\n') + rootObj.export( + sys.stdout, 0, name_=rootTag, + namespacedef_='xmlns:NS="http://www.barueri.sp.gov.br/nfe"') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def parseLiteral(inFileName, silence=False, print_warnings=True): + parser = None + doc = parsexml_(inFileName, parser) + gds_collector = GdsCollector_() + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteListarArquivos' + rootClass = NFeLoteListarArquivos + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + # Enable Python to collect the space used by the DOM. + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + sys.stdout.write('#from NFeLoteListarArquivo import *\n\n') + sys.stdout.write('import NFeLoteListarArquivo as model_\n\n') + sys.stdout.write('rootObj = model_.rootClass(\n') + rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) + sys.stdout.write(')\n') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def main(): + args = sys.argv[1:] + if len(args) == 1: + parse(args[0]) + else: + usage() + + +if __name__ == '__main__': + #import pdb; pdb.set_trace() + main() + +RenameMappings_ = { +} + +# +# Mapping of namespaces to types defined in them +# and the file in which each is defined. +# simpleTypes are marked "ST" and complexTypes "CT". +NamespaceToDefMappings_ = {'http://www.barueri.sp.gov.br/nfe': [('tsSitucaoArquivoRPS', + '../../schemas/barueri/NFeLoteListarArquivos.v1.xsd', + 'ST')]} + +__all__ = [ + "NFeLoteListarArquivos" +] diff --git a/nfselib/barueri/NFeLoteStatusArquivo.py b/nfselib/barueri/NFeLoteStatusArquivo.py new file mode 100644 index 0000000..af8d7d2 --- /dev/null +++ b/nfselib/barueri/NFeLoteStatusArquivo.py @@ -0,0 +1,1347 @@ +#TODO + +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# +# Generated Thu Apr 13 03:37:40 2023 by generateDS.py version 2.41.3. +# Python 3.8.10 (default, Mar 13 2023, 10:26:41) [GCC 9.4.0] +# +# Command line options: +# ('-o', 'NFeLoteStatusArquivo.py') +# +# Command line arguments: +# ../../schemas/barueri/NFeLoteStatusArquivo.v1.xsd +# +# Command line: +# /home/andre/.local/bin/generateDS -o "NFeLoteStatusArquivo.py" ../../schemas/barueri/NFeLoteStatusArquivo.v1.xsd +# +# Current working directory (os.getcwd()): +# barueri +# + +import sys +try: + ModulenotfoundExp_ = ModuleNotFoundError +except NameError: + ModulenotfoundExp_ = ImportError +from six.moves import zip_longest +import os +import re as re_ +import base64 +import datetime as datetime_ +import decimal as decimal_ +from lxml import etree as etree_ + + +Validate_simpletypes_ = True +SaveElementTreeNode = True +TagNamePrefix = "" +if sys.version_info.major == 2: + BaseStrType_ = basestring +else: + BaseStrType_ = str + + +def parsexml_(infile, parser=None, **kwargs): + if parser is None: + # Use the lxml ElementTree compatible parser so that, e.g., + # we ignore comments. + try: + parser = etree_.ETCompatXMLParser() + except AttributeError: + # fallback to xml.etree + parser = etree_.XMLParser() + try: + if isinstance(infile, os.PathLike): + infile = os.path.join(infile) + except AttributeError: + pass + doc = etree_.parse(infile, parser=parser, **kwargs) + return doc + +def parsexmlstring_(instring, parser=None, **kwargs): + if parser is None: + # Use the lxml ElementTree compatible parser so that, e.g., + # we ignore comments. + try: + parser = etree_.ETCompatXMLParser() + except AttributeError: + # fallback to xml.etree + parser = etree_.XMLParser() + element = etree_.fromstring(instring, parser=parser, **kwargs) + return element + +# +# Namespace prefix definition table (and other attributes, too) +# +# The module generatedsnamespaces, if it is importable, must contain +# a dictionary named GeneratedsNamespaceDefs. This Python dictionary +# should map element type names (strings) to XML schema namespace prefix +# definitions. The export method for any class for which there is +# a namespace prefix definition, will export that definition in the +# XML representation of that element. See the export method of +# any generated element type class for an example of the use of this +# table. +# A sample table is: +# +# # File: generatedsnamespaces.py +# +# GenerateDSNamespaceDefs = { +# "ElementtypeA": "http://www.xxx.com/namespaceA", +# "ElementtypeB": "http://www.xxx.com/namespaceB", +# } +# +# Additionally, the generatedsnamespaces module can contain a python +# dictionary named GenerateDSNamespaceTypePrefixes that associates element +# types with the namespace prefixes that are to be added to the +# "xsi:type" attribute value. See the _exportAttributes method of +# any generated element type and the generation of "xsi:type" for an +# example of the use of this table. +# An example table: +# +# # File: generatedsnamespaces.py +# +# GenerateDSNamespaceTypePrefixes = { +# "ElementtypeC": "aaa:", +# "ElementtypeD": "bbb:", +# } +# + +try: + from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ +except ModulenotfoundExp_ : + GenerateDSNamespaceDefs_ = {} +try: + from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ +except ModulenotfoundExp_ : + GenerateDSNamespaceTypePrefixes_ = {} + +# +# You can replace the following class definition by defining an +# importable module named "generatedscollector" containing a class +# named "GdsCollector". See the default class definition below for +# clues about the possible content of that class. +# +try: + from generatedscollector import GdsCollector as GdsCollector_ +except ModulenotfoundExp_ : + + class GdsCollector_(object): + + def __init__(self, messages=None): + if messages is None: + self.messages = [] + else: + self.messages = messages + + def add_message(self, msg): + self.messages.append(msg) + + def get_messages(self): + return self.messages + + def clear_messages(self): + self.messages = [] + + def print_messages(self): + for msg in self.messages: + print("Warning: {}".format(msg)) + + def write_messages(self, outstream): + for msg in self.messages: + outstream.write("Warning: {}\n".format(msg)) + + +# +# The super-class for enum types +# + +try: + from enum import Enum +except ModulenotfoundExp_ : + Enum = object + +# +# The root super-class for element type classes +# +# Calls to the methods in these classes are generated by generateDS.py. +# You can replace these methods by re-implementing the following class +# in a module named generatedssuper.py. + +try: + from generatedssuper import GeneratedsSuper +except ModulenotfoundExp_ as exp: + try: + from generatedssupersuper import GeneratedsSuperSuper + except ModulenotfoundExp_ as exp: + class GeneratedsSuperSuper(object): + pass + + class GeneratedsSuper(GeneratedsSuperSuper): + __hash__ = object.__hash__ + tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') + class _FixedOffsetTZ(datetime_.tzinfo): + def __init__(self, offset, name): + self.__offset = datetime_.timedelta(minutes=offset) + self.__name = name + def utcoffset(self, dt): + return self.__offset + def tzname(self, dt): + return self.__name + def dst(self, dt): + return None + def __str__(self): + settings = { + 'str_pretty_print': True, + 'str_indent_level': 0, + 'str_namespaceprefix': '', + 'str_name': self.__class__.__name__, + 'str_namespacedefs': '', + } + for n in settings: + if hasattr(self, n): + settings[n] = getattr(self, n) + if sys.version_info.major == 2: + from StringIO import StringIO + else: + from io import StringIO + output = StringIO() + self.export( + output, + settings['str_indent_level'], + pretty_print=settings['str_pretty_print'], + namespaceprefix_=settings['str_namespaceprefix'], + name_=settings['str_name'], + namespacedef_=settings['str_namespacedefs'] + ) + strval = output.getvalue() + output.close() + return strval + def gds_format_string(self, input_data, input_name=''): + return input_data + def gds_parse_string(self, input_data, node=None, input_name=''): + return input_data + def gds_validate_string(self, input_data, node=None, input_name=''): + if not input_data: + return '' + else: + return input_data + def gds_format_base64(self, input_data, input_name=''): + return base64.b64encode(input_data).decode('ascii') + def gds_validate_base64(self, input_data, node=None, input_name=''): + return input_data + def gds_format_integer(self, input_data, input_name=''): + return '%d' % int(input_data) + def gds_parse_integer(self, input_data, node=None, input_name=''): + try: + ival = int(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires integer value: %s' % exp) + return ival + def gds_validate_integer(self, input_data, node=None, input_name=''): + try: + value = int(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires integer value') + return value + def gds_format_integer_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_integer_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + int(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of integer values') + return values + def gds_format_float(self, input_data, input_name=''): + return ('%.15f' % float(input_data)).rstrip('0') + def gds_parse_float(self, input_data, node=None, input_name=''): + try: + fval_ = float(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires float or double value: %s' % exp) + return fval_ + def gds_validate_float(self, input_data, node=None, input_name=''): + try: + value = float(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires float value') + return value + def gds_format_float_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_float_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + float(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of float values') + return values + def gds_format_decimal(self, input_data, input_name=''): + return_value = '%s' % input_data + if '.' in return_value: + return_value = return_value.rstrip('0') + if return_value.endswith('.'): + return_value = return_value.rstrip('.') + return return_value + def gds_parse_decimal(self, input_data, node=None, input_name=''): + try: + decimal_value = decimal_.Decimal(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires decimal value') + return decimal_value + def gds_validate_decimal(self, input_data, node=None, input_name=''): + try: + value = decimal_.Decimal(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires decimal value') + return value + def gds_format_decimal_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return ' '.join([self.gds_format_decimal(item) for item in input_data]) + def gds_validate_decimal_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + decimal_.Decimal(value) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires sequence of decimal values') + return values + def gds_format_double(self, input_data, input_name=''): + return '%s' % input_data + def gds_parse_double(self, input_data, node=None, input_name=''): + try: + fval_ = float(input_data) + except (TypeError, ValueError) as exp: + raise_parse_error(node, 'Requires double or float value: %s' % exp) + return fval_ + def gds_validate_double(self, input_data, node=None, input_name=''): + try: + value = float(input_data) + except (TypeError, ValueError): + raise_parse_error(node, 'Requires double or float value') + return value + def gds_format_double_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_double_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + try: + float(value) + except (TypeError, ValueError): + raise_parse_error( + node, 'Requires sequence of double or float values') + return values + def gds_format_boolean(self, input_data, input_name=''): + return ('%s' % input_data).lower() + def gds_parse_boolean(self, input_data, node=None, input_name=''): + input_data = input_data.strip() + if input_data in ('true', '1'): + bval = True + elif input_data in ('false', '0'): + bval = False + else: + raise_parse_error(node, 'Requires boolean value') + return bval + def gds_validate_boolean(self, input_data, node=None, input_name=''): + if input_data not in (True, 1, False, 0, ): + raise_parse_error( + node, + 'Requires boolean value ' + '(one of True, 1, False, 0)') + return input_data + def gds_format_boolean_list(self, input_data, input_name=''): + if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): + input_data = [str(s) for s in input_data] + return '%s' % ' '.join(input_data) + def gds_validate_boolean_list( + self, input_data, node=None, input_name=''): + values = input_data.split() + for value in values: + value = self.gds_parse_boolean(value, node, input_name) + if value not in (True, 1, False, 0, ): + raise_parse_error( + node, + 'Requires sequence of boolean values ' + '(one of True, 1, False, 0)') + return values + def gds_validate_datetime(self, input_data, node=None, input_name=''): + return input_data + def gds_format_datetime(self, input_data, input_name=''): + if input_data.microsecond == 0: + _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( + input_data.year, + input_data.month, + input_data.day, + input_data.hour, + input_data.minute, + input_data.second, + ) + else: + _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( + input_data.year, + input_data.month, + input_data.day, + input_data.hour, + input_data.minute, + input_data.second, + ('%f' % (float(input_data.microsecond) / 1000000))[2:], + ) + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) + return _svalue + @classmethod + def gds_parse_datetime(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + time_parts = input_data.split('.') + if len(time_parts) > 1: + micro_seconds = int(float('0.' + time_parts[1]) * 1000000) + input_data = '%s.%s' % ( + time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) + dt = datetime_.datetime.strptime( + input_data, '%Y-%m-%dT%H:%M:%S.%f') + else: + dt = datetime_.datetime.strptime( + input_data, '%Y-%m-%dT%H:%M:%S') + dt = dt.replace(tzinfo=tz) + return dt + def gds_validate_date(self, input_data, node=None, input_name=''): + return input_data + def gds_format_date(self, input_data, input_name=''): + _svalue = '%04d-%02d-%02d' % ( + input_data.year, + input_data.month, + input_data.day, + ) + try: + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format( + hours, minutes) + except AttributeError: + pass + return _svalue + @classmethod + def gds_parse_date(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') + dt = dt.replace(tzinfo=tz) + return dt.date() + def gds_validate_time(self, input_data, node=None, input_name=''): + return input_data + def gds_format_time(self, input_data, input_name=''): + if input_data.microsecond == 0: + _svalue = '%02d:%02d:%02d' % ( + input_data.hour, + input_data.minute, + input_data.second, + ) + else: + _svalue = '%02d:%02d:%02d.%s' % ( + input_data.hour, + input_data.minute, + input_data.second, + ('%f' % (float(input_data.microsecond) / 1000000))[2:], + ) + if input_data.tzinfo is not None: + tzoff = input_data.tzinfo.utcoffset(input_data) + if tzoff is not None: + total_seconds = tzoff.seconds + (86400 * tzoff.days) + if total_seconds == 0: + _svalue += 'Z' + else: + if total_seconds < 0: + _svalue += '-' + total_seconds *= -1 + else: + _svalue += '+' + hours = total_seconds // 3600 + minutes = (total_seconds - (hours * 3600)) // 60 + _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) + return _svalue + def gds_validate_simple_patterns(self, patterns, target): + # pat is a list of lists of strings/patterns. + # The target value must match at least one of the patterns + # in order for the test to succeed. + found1 = True + target = str(target) + for patterns1 in patterns: + found2 = False + for patterns2 in patterns1: + mo = re_.search(patterns2, target) + if mo is not None and len(mo.group(0)) == len(target): + found2 = True + break + if not found2: + found1 = False + break + return found1 + @classmethod + def gds_parse_time(cls, input_data): + tz = None + if input_data[-1] == 'Z': + tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') + input_data = input_data[:-1] + else: + results = GeneratedsSuper.tzoff_pattern.search(input_data) + if results is not None: + tzoff_parts = results.group(2).split(':') + tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) + if results.group(1) == '-': + tzoff *= -1 + tz = GeneratedsSuper._FixedOffsetTZ( + tzoff, results.group(0)) + input_data = input_data[:-6] + if len(input_data.split('.')) > 1: + dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') + else: + dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') + dt = dt.replace(tzinfo=tz) + return dt.time() + def gds_check_cardinality_( + self, value, input_name, + min_occurs=0, max_occurs=1, required=None): + if value is None: + length = 0 + elif isinstance(value, list): + length = len(value) + else: + length = 1 + if required is not None : + if required and length < 1: + self.gds_collector_.add_message( + "Required value {}{} is missing".format( + input_name, self.gds_get_node_lineno_())) + if length < min_occurs: + self.gds_collector_.add_message( + "Number of values for {}{} is below " + "the minimum allowed, " + "expected at least {}, found {}".format( + input_name, self.gds_get_node_lineno_(), + min_occurs, length)) + elif length > max_occurs: + self.gds_collector_.add_message( + "Number of values for {}{} is above " + "the maximum allowed, " + "expected at most {}, found {}".format( + input_name, self.gds_get_node_lineno_(), + max_occurs, length)) + def gds_validate_builtin_ST_( + self, validator, value, input_name, + min_occurs=None, max_occurs=None, required=None): + if value is not None: + try: + validator(value, input_name=input_name) + except GDSParseError as parse_error: + self.gds_collector_.add_message(str(parse_error)) + def gds_validate_defined_ST_( + self, validator, value, input_name, + min_occurs=None, max_occurs=None, required=None): + if value is not None: + try: + validator(value) + except GDSParseError as parse_error: + self.gds_collector_.add_message(str(parse_error)) + def gds_str_lower(self, instring): + return instring.lower() + def get_path_(self, node): + path_list = [] + self.get_path_list_(node, path_list) + path_list.reverse() + path = '/'.join(path_list) + return path + Tag_strip_pattern_ = re_.compile(r'\{.*\}') + def get_path_list_(self, node, path_list): + if node is None: + return + tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) + if tag: + path_list.append(tag) + self.get_path_list_(node.getparent(), path_list) + def get_class_obj_(self, node, default_class=None): + class_obj1 = default_class + if 'xsi' in node.nsmap: + classname = node.get('{%s}type' % node.nsmap['xsi']) + if classname is not None: + names = classname.split(':') + if len(names) == 2: + classname = names[1] + class_obj2 = globals().get(classname) + if class_obj2 is not None: + class_obj1 = class_obj2 + return class_obj1 + def gds_build_any(self, node, type_name=None): + # provide default value in case option --disable-xml is used. + content = "" + content = etree_.tostring(node, encoding="unicode") + return content + @classmethod + def gds_reverse_node_mapping(cls, mapping): + return dict(((v, k) for k, v in mapping.items())) + @staticmethod + def gds_encode(instring): + if sys.version_info.major == 2: + if ExternalEncoding: + encoding = ExternalEncoding + else: + encoding = 'utf-8' + return instring.encode(encoding) + else: + return instring + @staticmethod + def convert_unicode(instring): + if isinstance(instring, str): + result = quote_xml(instring) + elif sys.version_info.major == 2 and isinstance(instring, unicode): + result = quote_xml(instring).encode('utf8') + else: + result = GeneratedsSuper.gds_encode(str(instring)) + return result + def __eq__(self, other): + def excl_select_objs_(obj): + return (obj[0] != 'parent_object_' and + obj[0] != 'gds_collector_') + if type(self) != type(other): + return False + return all(x == y for x, y in zip_longest( + filter(excl_select_objs_, self.__dict__.items()), + filter(excl_select_objs_, other.__dict__.items()))) + def __ne__(self, other): + return not self.__eq__(other) + # Django ETL transform hooks. + def gds_djo_etl_transform(self): + pass + def gds_djo_etl_transform_db_obj(self, dbobj): + pass + # SQLAlchemy ETL transform hooks. + def gds_sqa_etl_transform(self): + return 0, None + def gds_sqa_etl_transform_db_obj(self, dbobj): + pass + def gds_get_node_lineno_(self): + if (hasattr(self, "gds_elementtree_node_") and + self.gds_elementtree_node_ is not None): + return ' near line {}'.format( + self.gds_elementtree_node_.sourceline) + else: + return "" + + + def getSubclassFromModule_(module, class_): + '''Get the subclass of a class from a specific module.''' + name = class_.__name__ + 'Sub' + if hasattr(module, name): + return getattr(module, name) + else: + return None + + +# +# If you have installed IPython you can uncomment and use the following. +# IPython is available from http://ipython.scipy.org/. +# + +## from IPython.Shell import IPShellEmbed +## args = '' +## ipshell = IPShellEmbed(args, +## banner = 'Dropping into IPython', +## exit_msg = 'Leaving Interpreter, back to program.') + +# Then use the following line where and when you want to drop into the +# IPython shell: +# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') + +# +# Globals +# + +ExternalEncoding = '' +# Set this to false in order to deactivate during export, the use of +# name space prefixes captured from the input document. +UseCapturedNS_ = True +CapturedNsmap_ = {} +Tag_pattern_ = re_.compile(r'({.*})?(.*)') +String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") +Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') +CDATA_pattern_ = re_.compile(r"", re_.DOTALL) + +# Change this to redirect the generated superclass module to use a +# specific subclass module. +CurrentSubclassModule_ = None + +# +# Support/utility functions. +# + + +def showIndent(outfile, level, pretty_print=True): + if pretty_print: + for idx in range(level): + outfile.write(' ') + + +def quote_xml(inStr): + "Escape markup chars, but do not modify CDATA sections." + if not inStr: + return '' + s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) + s2 = '' + pos = 0 + matchobjects = CDATA_pattern_.finditer(s1) + for mo in matchobjects: + s3 = s1[pos:mo.start()] + s2 += quote_xml_aux(s3) + s2 += s1[mo.start():mo.end()] + pos = mo.end() + s3 = s1[pos:] + s2 += quote_xml_aux(s3) + return s2 + + +def quote_xml_aux(inStr): + s1 = inStr.replace('&', '&') + s1 = s1.replace('<', '<') + s1 = s1.replace('>', '>') + return s1 + + +def quote_attrib(inStr): + s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) + s1 = s1.replace('&', '&') + s1 = s1.replace('<', '<') + s1 = s1.replace('>', '>') + s1 = s1.replace('\n', ' ') + if '"' in s1: + if "'" in s1: + s1 = '"%s"' % s1.replace('"', """) + else: + s1 = "'%s'" % s1 + else: + s1 = '"%s"' % s1 + return s1 + + +def quote_python(inStr): + s1 = inStr + if s1.find("'") == -1: + if s1.find('\n') == -1: + return "'%s'" % s1 + else: + return "'''%s'''" % s1 + else: + if s1.find('"') != -1: + s1 = s1.replace('"', '\\"') + if s1.find('\n') == -1: + return '"%s"' % s1 + else: + return '"""%s"""' % s1 + + +def get_all_text_(node): + if node.text is not None: + text = node.text + else: + text = '' + for child in node: + if child.tail is not None: + text += child.tail + return text + + +def find_attr_value_(attr_name, node): + attrs = node.attrib + attr_parts = attr_name.split(':') + value = None + if len(attr_parts) == 1: + value = attrs.get(attr_name) + elif len(attr_parts) == 2: + prefix, name = attr_parts + if prefix == 'xml': + namespace = 'http://www.w3.org/XML/1998/namespace' + else: + namespace = node.nsmap.get(prefix) + if namespace is not None: + value = attrs.get('{%s}%s' % (namespace, name, )) + return value + + +def encode_str_2_3(instr): + return instr + + +class GDSParseError(Exception): + pass + + +def raise_parse_error(node, msg): + if node is not None: + msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) + raise GDSParseError(msg) + + +class MixedContainer: + # Constants for category: + CategoryNone = 0 + CategoryText = 1 + CategorySimple = 2 + CategoryComplex = 3 + # Constants for content_type: + TypeNone = 0 + TypeText = 1 + TypeString = 2 + TypeInteger = 3 + TypeFloat = 4 + TypeDecimal = 5 + TypeDouble = 6 + TypeBoolean = 7 + TypeBase64 = 8 + def __init__(self, category, content_type, name, value): + self.category = category + self.content_type = content_type + self.name = name + self.value = value + def getCategory(self): + return self.category + def getContenttype(self, content_type): + return self.content_type + def getValue(self): + return self.value + def getName(self): + return self.name + def export(self, outfile, level, name, namespace, + pretty_print=True): + if self.category == MixedContainer.CategoryText: + # Prevent exporting empty content as empty lines. + if self.value.strip(): + outfile.write(self.value) + elif self.category == MixedContainer.CategorySimple: + self.exportSimple(outfile, level, name) + else: # category == MixedContainer.CategoryComplex + self.value.export( + outfile, level, namespace, name_=name, + pretty_print=pretty_print) + def exportSimple(self, outfile, level, name): + if self.content_type == MixedContainer.TypeString: + outfile.write('<%s>%s' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeInteger or \ + self.content_type == MixedContainer.TypeBoolean: + outfile.write('<%s>%d' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeFloat or \ + self.content_type == MixedContainer.TypeDecimal: + outfile.write('<%s>%f' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeDouble: + outfile.write('<%s>%g' % ( + self.name, self.value, self.name)) + elif self.content_type == MixedContainer.TypeBase64: + outfile.write('<%s>%s' % ( + self.name, + base64.b64encode(self.value), + self.name)) + def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): + if self.category == MixedContainer.CategoryText: + # Prevent exporting empty content as empty lines. + if self.value.strip(): + if len(element) > 0: + if element[-1].tail is None: + element[-1].tail = self.value + else: + element[-1].tail += self.value + else: + if element.text is None: + element.text = self.value + else: + element.text += self.value + elif self.category == MixedContainer.CategorySimple: + subelement = etree_.SubElement( + element, '%s' % self.name) + subelement.text = self.to_etree_simple() + else: # category == MixedContainer.CategoryComplex + self.value.to_etree(element) + def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): + if self.content_type == MixedContainer.TypeString: + text = self.value + elif (self.content_type == MixedContainer.TypeInteger or + self.content_type == MixedContainer.TypeBoolean): + text = '%d' % self.value + elif (self.content_type == MixedContainer.TypeFloat or + self.content_type == MixedContainer.TypeDecimal): + text = '%f' % self.value + elif self.content_type == MixedContainer.TypeDouble: + text = '%g' % self.value + elif self.content_type == MixedContainer.TypeBase64: + text = '%s' % base64.b64encode(self.value) + return text + def exportLiteral(self, outfile, level, name): + if self.category == MixedContainer.CategoryText: + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( + self.category, self.content_type, + self.name, self.value)) + elif self.category == MixedContainer.CategorySimple: + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( + self.category, self.content_type, + self.name, self.value)) + else: # category == MixedContainer.CategoryComplex + showIndent(outfile, level) + outfile.write( + 'model_.MixedContainer(%d, %d, "%s",\n' % ( + self.category, self.content_type, self.name,)) + self.value.exportLiteral(outfile, level + 1) + showIndent(outfile, level) + outfile.write(')\n') + + +class MemberSpec_(object): + def __init__(self, name='', data_type='', container=0, + optional=0, child_attrs=None, choice=None): + self.name = name + self.data_type = data_type + self.container = container + self.child_attrs = child_attrs + self.choice = choice + self.optional = optional + def set_name(self, name): self.name = name + def get_name(self): return self.name + def set_data_type(self, data_type): self.data_type = data_type + def get_data_type_chain(self): return self.data_type + def get_data_type(self): + if isinstance(self.data_type, list): + if len(self.data_type) > 0: + return self.data_type[-1] + else: + return 'xs:string' + else: + return self.data_type + def set_container(self, container): self.container = container + def get_container(self): return self.container + def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs + def get_child_attrs(self): return self.child_attrs + def set_choice(self, choice): self.choice = choice + def get_choice(self): return self.choice + def set_optional(self, optional): self.optional = optional + def get_optional(self): return self.optional + + +def _cast(typ, value): + if typ is None or value is None: + return value + return typ(value) + +# +# Data representation classes. +# + + +class NFeLoteStatusArquivo(GeneratedsSuper): + """InscricaoMunicipal -- Numero da inscri + ç + ã + o municipal do contribuinte na Prefeitura de Barueri. + CPFCNPJContrib -- CNPJ/CPF do contribuinte + ProtocoloRemessa -- C + ó + digo do protocolo de Remessa retornado pelo m + é + todo NFeLoteEnviarArquivo. + + """ + __hash__ = GeneratedsSuper.__hash__ + subclass = None + superclass = None + def __init__(self, InscricaoMunicipal=None, CPFCNPJContrib=None, ProtocoloRemessa=None, gds_collector_=None, **kwargs_): + self.gds_collector_ = gds_collector_ + self.gds_elementtree_node_ = None + self.original_tagname_ = None + self.parent_object_ = kwargs_.get('parent_object_') + self.ns_prefix_ = None + self.InscricaoMunicipal = InscricaoMunicipal + self.InscricaoMunicipal_nsprefix_ = None + self.CPFCNPJContrib = CPFCNPJContrib + self.CPFCNPJContrib_nsprefix_ = None + self.ProtocoloRemessa = ProtocoloRemessa + self.ProtocoloRemessa_nsprefix_ = None + def factory(*args_, **kwargs_): + if CurrentSubclassModule_ is not None: + subclass = getSubclassFromModule_( + CurrentSubclassModule_, NFeLoteStatusArquivo) + if subclass is not None: + return subclass(*args_, **kwargs_) + if NFeLoteStatusArquivo.subclass: + return NFeLoteStatusArquivo.subclass(*args_, **kwargs_) + else: + return NFeLoteStatusArquivo(*args_, **kwargs_) + factory = staticmethod(factory) + def get_ns_prefix_(self): + return self.ns_prefix_ + def set_ns_prefix_(self, ns_prefix): + self.ns_prefix_ = ns_prefix + def get_InscricaoMunicipal(self): + return self.InscricaoMunicipal + def set_InscricaoMunicipal(self, InscricaoMunicipal): + self.InscricaoMunicipal = InscricaoMunicipal + def get_CPFCNPJContrib(self): + return self.CPFCNPJContrib + def set_CPFCNPJContrib(self, CPFCNPJContrib): + self.CPFCNPJContrib = CPFCNPJContrib + def get_ProtocoloRemessa(self): + return self.ProtocoloRemessa + def set_ProtocoloRemessa(self, ProtocoloRemessa): + self.ProtocoloRemessa = ProtocoloRemessa + def _hasContent(self): + if ( + self.InscricaoMunicipal is not None or + self.CPFCNPJContrib is not None or + self.ProtocoloRemessa is not None + ): + return True + else: + return False + def export(self, outfile, level, namespaceprefix_='', namespacedef_=' xmlns:None="http://www.barueri.sp.gov.br/nfe" ', name_='NFeLoteStatusArquivo', pretty_print=True): + imported_ns_def_ = GenerateDSNamespaceDefs_.get('NFeLoteStatusArquivo') + if imported_ns_def_ is not None: + namespacedef_ = imported_ns_def_ + if pretty_print: + eol_ = '\n' + else: + eol_ = '' + if self.original_tagname_ is not None and name_ == 'NFeLoteStatusArquivo': + name_ = self.original_tagname_ + if UseCapturedNS_ and self.ns_prefix_: + namespaceprefix_ = self.ns_prefix_ + ':' + showIndent(outfile, level, pretty_print) + outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) + already_processed = set() + self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='NFeLoteStatusArquivo') + if self._hasContent(): + outfile.write('>%s' % (eol_, )) + self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='NFeLoteStatusArquivo', pretty_print=pretty_print) + showIndent(outfile, level, pretty_print) + outfile.write('%s' % (namespaceprefix_, name_, eol_)) + else: + outfile.write('/>%s' % (eol_, )) + def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='NFeLoteStatusArquivo'): + pass + def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_=' xmlns:None="http://www.barueri.sp.gov.br/nfe" ', name_='NFeLoteStatusArquivo', fromsubclass_=False, pretty_print=True): + if pretty_print: + eol_ = '\n' + else: + eol_ = '' + if self.InscricaoMunicipal is not None: + namespaceprefix_ = self.InscricaoMunicipal_nsprefix_ + ':' if (UseCapturedNS_ and self.InscricaoMunicipal_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sInscricaoMunicipal>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InscricaoMunicipal), input_name='InscricaoMunicipal')), namespaceprefix_ , eol_)) + if self.CPFCNPJContrib is not None: + namespaceprefix_ = self.CPFCNPJContrib_nsprefix_ + ':' if (UseCapturedNS_ and self.CPFCNPJContrib_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sCPFCNPJContrib>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CPFCNPJContrib), input_name='CPFCNPJContrib')), namespaceprefix_ , eol_)) + if self.ProtocoloRemessa is not None: + namespaceprefix_ = self.ProtocoloRemessa_nsprefix_ + ':' if (UseCapturedNS_ and self.ProtocoloRemessa_nsprefix_) else '' + showIndent(outfile, level, pretty_print) + outfile.write('<%sProtocoloRemessa>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ProtocoloRemessa), input_name='ProtocoloRemessa')), namespaceprefix_ , eol_)) + def build(self, node, gds_collector_=None): + self.gds_collector_ = gds_collector_ + if SaveElementTreeNode: + self.gds_elementtree_node_ = node + already_processed = set() + self.ns_prefix_ = node.prefix + self._buildAttributes(node, node.attrib, already_processed) + for child in node: + nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] + self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) + return self + def _buildAttributes(self, node, attrs, already_processed): + pass + def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): + if nodeName_ == 'InscricaoMunicipal': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'InscricaoMunicipal') + value_ = self.gds_validate_string(value_, node, 'InscricaoMunicipal') + self.InscricaoMunicipal = value_ + self.InscricaoMunicipal_nsprefix_ = child_.prefix + elif nodeName_ == 'CPFCNPJContrib': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'CPFCNPJContrib') + value_ = self.gds_validate_string(value_, node, 'CPFCNPJContrib') + self.CPFCNPJContrib = value_ + self.CPFCNPJContrib_nsprefix_ = child_.prefix + elif nodeName_ == 'ProtocoloRemessa': + value_ = child_.text + value_ = self.gds_parse_string(value_, node, 'ProtocoloRemessa') + value_ = self.gds_validate_string(value_, node, 'ProtocoloRemessa') + self.ProtocoloRemessa = value_ + self.ProtocoloRemessa_nsprefix_ = child_.prefix +# end class NFeLoteStatusArquivo + + +GDSClassesMapping = { +} + + +USAGE_TEXT = """ +Usage: python .py [ -s ] +""" + + +def usage(): + print(USAGE_TEXT) + sys.exit(1) + + +def get_root_tag(node): + tag = Tag_pattern_.match(node.tag).groups()[-1] + prefix_tag = TagNamePrefix + tag + rootClass = GDSClassesMapping.get(prefix_tag) + if rootClass is None: + rootClass = globals().get(prefix_tag) + return tag, rootClass + + +def get_required_ns_prefix_defs(rootNode): + '''Get all name space prefix definitions required in this XML doc. + Return a dictionary of definitions and a char string of definitions. + ''' + nsmap = { + prefix: uri + for node in rootNode.iter() + for (prefix, uri) in node.nsmap.items() + if prefix is not None + } + namespacedefs = ' '.join([ + 'xmlns:{}="{}"'.format(prefix, uri) + for prefix, uri in nsmap.items() + ]) + return nsmap, namespacedefs + + +def parse(inFileName, silence=False, print_warnings=True): + global CapturedNsmap_ + gds_collector = GdsCollector_() + parser = None + doc = parsexml_(inFileName, parser) + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteStatusArquivo' + rootClass = NFeLoteStatusArquivo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + sys.stdout.write('\n') + rootObj.export( + sys.stdout, 0, name_=rootTag, + namespacedef_=namespacedefs, + pretty_print=True) + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def parseEtree(inFileName, silence=False, print_warnings=True, + mapping=None, reverse_mapping=None, nsmap=None): + parser = None + doc = parsexml_(inFileName, parser) + gds_collector = GdsCollector_() + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteStatusArquivo' + rootClass = NFeLoteStatusArquivo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + if mapping is None: + mapping = {} + if reverse_mapping is None: + reverse_mapping = {} + rootElement = rootObj.to_etree( + None, name_=rootTag, mapping_=mapping, + reverse_mapping_=reverse_mapping, nsmap_=nsmap) + reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) + # Enable Python to collect the space used by the DOM. + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + content = etree_.tostring( + rootElement, pretty_print=True, + xml_declaration=True, encoding="utf-8") + sys.stdout.write(str(content)) + sys.stdout.write('\n') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj, rootElement, mapping, reverse_node_mapping + + +def parseString(inString, silence=False, print_warnings=True): + '''Parse a string, create the object tree, and export it. + + Arguments: + - inString -- A string. This XML fragment should not start + with an XML declaration containing an encoding. + - silence -- A boolean. If False, export the object. + Returns -- The root object in the tree. + ''' + parser = None + rootNode= parsexmlstring_(inString, parser) + gds_collector = GdsCollector_() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteStatusArquivo' + rootClass = NFeLoteStatusArquivo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + if not SaveElementTreeNode: + rootNode = None + if not silence: + sys.stdout.write('\n') + rootObj.export( + sys.stdout, 0, name_=rootTag, + namespacedef_='') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def parseLiteral(inFileName, silence=False, print_warnings=True): + parser = None + doc = parsexml_(inFileName, parser) + gds_collector = GdsCollector_() + rootNode = doc.getroot() + rootTag, rootClass = get_root_tag(rootNode) + if rootClass is None: + rootTag = 'NFeLoteStatusArquivo' + rootClass = NFeLoteStatusArquivo + rootObj = rootClass.factory() + rootObj.build(rootNode, gds_collector_=gds_collector) + # Enable Python to collect the space used by the DOM. + if not SaveElementTreeNode: + doc = None + rootNode = None + if not silence: + sys.stdout.write('#from NFeLoteStatusArquivo import *\n\n') + sys.stdout.write('import NFeLoteStatusArquivo as model_\n\n') + sys.stdout.write('rootObj = model_.rootClass(\n') + rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) + sys.stdout.write(')\n') + if print_warnings and len(gds_collector.get_messages()) > 0: + separator = ('-' * 50) + '\n' + sys.stderr.write(separator) + sys.stderr.write('----- Warnings -- count: {} -----\n'.format( + len(gds_collector.get_messages()), )) + gds_collector.write_messages(sys.stderr) + sys.stderr.write(separator) + return rootObj + + +def main(): + args = sys.argv[1:] + if len(args) == 1: + parse(args[0]) + else: + usage() + + +if __name__ == '__main__': + #import pdb; pdb.set_trace() + main() + +RenameMappings_ = { +} + +# +# Mapping of namespaces to types defined in them +# and the file in which each is defined. +# simpleTypes are marked "ST" and complexTypes "CT". +NamespaceToDefMappings_ = {'http://www.barueri.sp.gov.br/nfe': []} + +__all__ = [ + "NFeLoteStatusArquivo" +] diff --git a/nfselib/barueri/exportador.py b/nfselib/barueri/exportador.py index 5a820cc..5080841 100644 --- a/nfselib/barueri/exportador.py +++ b/nfselib/barueri/exportador.py @@ -1,4 +1,3 @@ -# TODO: Enviar classes para erpbrasil.base class CampoPosicional: diff --git a/nfselib/barueri/generatedsnamespaces.py b/nfselib/barueri/generatedsnamespaces.py new file mode 100644 index 0000000..c784c6a --- /dev/null +++ b/nfselib/barueri/generatedsnamespaces.py @@ -0,0 +1,18 @@ +GenerateDSNamespaceDefs = { + "ConsultaNFeRecebidaCompetencia": 'xmlns="http://www.barueri.sp.gov.br/nfe" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:NS="http://www.barueri.sp.gov.br/nfe"', + "ConsultaNFeRecebidaNumero": 'xmlns="http://www.barueri.sp.gov.br/nfe" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:NS="http://www.barueri.sp.gov.br/nfe"', + "ConsultaNFeRecebidaPeriodo": 'xmlns="http://www.barueri.sp.gov.br/nfe" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:NS="http://www.barueri.sp.gov.br/nfe"', + "NFeLoteBaixarArquivo": 'xmlns="http://www.barueri.sp.gov.br/nfe" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:NS="http://www.barueri.sp.gov.br/nfe"', + "NFeLoteListarArquivos": 'xmlns="http://www.barueri.sp.gov.br/nfe" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:NS="http://www.barueri.sp.gov.br/nfe"', + "NFeLoteStatusArquivo": 'xmlns="http://www.barueri.sp.gov.br/nf" xmlns:p1=""', + "NFeLoteEnviarArquivo" : 'xmlns="http://www.barueri.sp.gov.br/nfe"' +} + +GenerateDSNamespaceTypePrefixes = { + "InscricaoMunicipal": 'tipos', + "CPFCNPJContrib": 'tipos', + "NomeArquivoRPS": 'tipos', + "ArquivoRPSBase64": 'tipos', + "ApenasValidaArq": 'tipos', + "cabecalho": 'ns2' +} diff --git a/schemas/barueri/ConsultaNFeRecebidaCompetencia.v1.xsd b/schemas/barueri/ConsultaNFeRecebidaCompetencia.v1.xsd new file mode 100644 index 0000000..f675594 --- /dev/null +++ b/schemas/barueri/ConsultaNFeRecebidaCompetencia.v1.xsd @@ -0,0 +1,25 @@ + + + + + + + + + Mês de Competência que Nota refere-se (AAAAMM). + + + + + CNPJ/CPF do Prestador do Serviço, ou seja, aquele que emitiu a nota ao Tomador + + + + + Número da pagina que deseja consulta, caso a pesquisa excede o número de registros permitido o resultado é disponibilizado em páginas + + + + + + \ No newline at end of file diff --git a/schemas/barueri/ConsultaNFeRecebidaNumero.v1.xsd b/schemas/barueri/ConsultaNFeRecebidaNumero.v1.xsd new file mode 100644 index 0000000..99ae4e2 --- /dev/null +++ b/schemas/barueri/ConsultaNFeRecebidaNumero.v1.xsd @@ -0,0 +1,20 @@ + + + + + + + + + CNPJ/CPF do Prestador do Serviço, ou seja, aquele que emitiu a nota ao Tomador + + + + + Numero da nota foi emitida para o tomador. + + + + + + \ No newline at end of file diff --git a/schemas/barueri/ConsultaNFeRecebidaPeriodo.v1.xsd b/schemas/barueri/ConsultaNFeRecebidaPeriodo.v1.xsd new file mode 100644 index 0000000..e9612d8 --- /dev/null +++ b/schemas/barueri/ConsultaNFeRecebidaPeriodo.v1.xsd @@ -0,0 +1,30 @@ + + + + + + + + + Intervalo inical de data em que a nota foi emitida para o tomador (AAAA-MM-DD). + + + + + Data Final em que a nota foi emitida para o tomador (AAAA-MM-DD). + + + + + CNPJ/CPF do Prestador do Serviço, ou seja, aquele que emitiu a nota ao Tomador + + + + + Número da pagina que deseja consulta, caso a pesquisa excede o número de registros permitido o resultado é disponibilizado em páginas + + + + + + \ No newline at end of file diff --git a/schemas/barueri/NFeLoteBaixarArquivo.v1.xsd b/schemas/barueri/NFeLoteBaixarArquivo.v1.xsd new file mode 100644 index 0000000..9849175 --- /dev/null +++ b/schemas/barueri/NFeLoteBaixarArquivo.v1.xsd @@ -0,0 +1,24 @@ + + + + + + + + Numero da inscrição municipal do contribuinte na Prefeitura de Barueri. + + + + + CNPJ/CPF do contribuinte + + + + + Nome do Arquivo de retorno que deseja baixar. Para obter a relação de arquivos a serem baixado utilize o método NFeLoteListarArquivos + + + + + + \ No newline at end of file diff --git a/schemas/barueri/NFeLoteEnviarArquivo.v1.xsd b/schemas/barueri/NFeLoteEnviarArquivo.v1.xsd new file mode 100644 index 0000000..0d75cd4 --- /dev/null +++ b/schemas/barueri/NFeLoteEnviarArquivo.v1.xsd @@ -0,0 +1,34 @@ + + + + + + + + Numero da inscrição municipal do contribuinte na Prefeitura de Barueri. + + + + + CNPJ/CPF do contribuinte + + + + + Nome do Arquivo do contribuinte que está sendo enviado para processamento + + + + + Flag para indicar se o arquivo deve gerar NFe. Caso deseje apenas validar o arquivo informar true, valor padrão é false + + + + + Conteúdo do Arquivo do contribuinte em Base64 + + + + + + \ No newline at end of file diff --git a/schemas/barueri/NFeLoteListarArquivos.v1.xsd b/schemas/barueri/NFeLoteListarArquivos.v1.xsd new file mode 100644 index 0000000..bfe9638 --- /dev/null +++ b/schemas/barueri/NFeLoteListarArquivos.v1.xsd @@ -0,0 +1,44 @@ + + + + + + + + Numero da inscrição municipal do contribuinte na Prefeitura de Barueri. + + + + + CNPJ/CPF do Prestador do contribuinte + + + + + Data de envio dos arquivos de remessa ao sistema NFe (AAAA-MM-DD). + + + + + Indicar a situação dos arquivos + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/schemas/barueri/NFeLoteStatusArquivo.v1.xsd b/schemas/barueri/NFeLoteStatusArquivo.v1.xsd new file mode 100644 index 0000000..1232feb --- /dev/null +++ b/schemas/barueri/NFeLoteStatusArquivo.v1.xsd @@ -0,0 +1,24 @@ + + + + + + + + Numero da inscrição municipal do contribuinte na Prefeitura de Barueri. + + + + + CNPJ/CPF do contribuinte + + + + + Código do protocolo de Remessa retornado pelo método NFeLoteEnviarArquivo. + + + + + + \ No newline at end of file diff --git a/scripts/README.md b/scripts/README.md new file mode 100644 index 0000000..b553e26 --- /dev/null +++ b/scripts/README.md @@ -0,0 +1 @@ +Nesta pasta colocamos os scripts utilizados para fazer o download e geração da biblioteca. diff --git a/scripts/generate.sh b/scripts/generate.sh new file mode 100644 index 0000000..ce386b6 --- /dev/null +++ b/scripts/generate.sh @@ -0,0 +1,2 @@ +pip install generateDS +generateDS -o nfselib/barueri schemas/ \ No newline at end of file