Browse Source

Criado classes de para serialização de xm

tags/0.1.5
Danimar Ribeiro 11 years ago
parent
commit
c0acf767da
  1. 2
      pytrustnfe/HttpClient.py
  2. 40
      pytrustnfe/Strings.py
  3. 10
      pytrustnfe/servicos/Comunicacao.py
  4. 13
      pytrustnfe/test/test_comunicacao.py
  5. 29
      pytrustnfe/test/test_xml_serializacao.py
  6. 67
      pytrustnfe/xml/DynamicXml.py
  7. 0
      pytrustnfe/xml/__init__.py

2
pytrustnfe/HttpClient.py

@ -27,7 +27,7 @@ class HttpClient(object):
try:
conexao.request(u'POST', post, xml, self._headers())
response = conexao.getresponse()
if response.status == '200':
if response.status == 200:
return response.read()
return response.read()
except Exception as e:

40
pytrustnfe/Strings.py

@ -0,0 +1,40 @@
'''
Created on Jun 17, 2015
@author: danimar
'''
CONSULTA_CADASTRO_COMPLETA = '<?xml version="1.0" encoding="utf-8"?>'\
'<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">'\
'<soap:Header>'\
'<nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2">'\
'<cUF>35</cUF><versaoDados>2.00</versaoDados>'\
'</nfeCabecMsg>'\
'</soap:Header>'\
'<soap:Body>'\
'<nfeDadosMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2">'\
'<ConsCad xmlns="http://www.portalfiscal.inf.br/nfe" versao="2.00">'\
'<infCons><xServ>CONS-CAD</xServ><UF>SP</UF><IE>606081249112</IE></infCons>'\
'</ConsCad></nfeDadosMsg>'\
'</soap:Body>'\
'</soap:Envelope>'
RETORNO_CONSULTA = '<?xml version="1.0" encoding="utf-8"?>'\
'<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'\
'<soap:Header><nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2">'\
'<cUF>35</cUF><versaoDados>2.00</versaoDados></nfeCabecMsg>'\
'</soap:Header><soap:Body>'\
'<consultaCadastro2Result xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2">'\
'<retConsCad versao="2.00" xmlns="http://www.portalfiscal.inf.br/nfe">'\
'<infCons><verAplic>SP_NFE_PL_008f</verAplic><cStat>111</cStat>'\
'<xMotivo>Consulta cadastro com uma ocorrência</xMotivo><UF>SP</UF>'\
'<IE>606081249112</IE><dhCons>2015-06-17T14:54:23-03:00</dhCons><cUF>35</cUF>'\
'<infCad><IE>606081249112</IE><CNPJ>02198926000169</CNPJ><UF>SP</UF><cSit>1</cSit>'\
'<indCredNFe>1</indCredNFe><indCredCTe>4</indCredCTe><xNome>C. R. TUNUSSI &amp; CIA. LTDA</xNome>'\
'<xRegApur>NORMAL - REGIME PERIÓDICO DE APURAÇÃO</xRegApur><CNAE>2825900</CNAE>'\
'<dIniAtiv>1997-11-17</dIniAtiv><dUltSit>1997-11-17</dUltSit><ender>'\
'<xLgr>RUA JOSE NICOLAU LUX</xLgr><nro>432</nro>'\
'<xBairro>CONJUNTO HABITACIONAL FRANCISCO DE CILLO (INOCOOP)</xBairro><cMun>3545803</cMun>'\
'<xMun>SANTA BARBARA D''OESTE</xMun><CEP>13457162</CEP></ender></infCad></infCons>'\
'</retConsCad></consultaCadastro2Result></soap:Body></soap:Envelope>'

10
pytrustnfe/servicos/Comunicacao.py

@ -15,6 +15,7 @@ logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.client').setLevel(logging.DEBUG)
logging.getLogger('suds.transport').setLevel(logging.DEBUG)
from pytrustnfe.Strings import CONSULTA_CADASTRO_COMPLETA
class Comunicacao(object):
@ -38,6 +39,15 @@ class Comunicacao(object):
return chave_temp, certificado_temp
def consulta_cadastro(self, obj_consulta):
chave, certificado = self._preparar_temp_pem()
client = HttpClient('nfe.fazenda.sp.gov.br', chave, certificado)
xml_retorno = client.post_xml('/ws/cadconsultacadastro2.asmx', CONSULTA_CADASTRO_COMPLETA)
obj = objectify.fromstring(xml_retorno)
return xml_retorno, obj
def envio_nfe(self):
chave, certificado = self._preparar_temp_pem()

13
pytrustnfe/test/test_comunicacao.py

@ -16,6 +16,19 @@ class test_comunicacao(unittest.TestCase):
caminho = os.path.dirname(__file__)
def test_consulta_cadastro(self):
try:
dir_pfx = '/home/danimar/Desktop/isotelha.pfx' #Hack
com = Comunicacao(dir_pfx, 'iso@#telha')
xml, objeto = com.consulta_cadastro(None)
print xml
print objeto
except Exception as e:
print(str(e))
#Teste temporario
def test_envio_without_mock(self):
try:

29
pytrustnfe/test/test_xml_serializacao.py

@ -0,0 +1,29 @@
#coding=utf-8
import unittest
from lxml.etree import Element, ElementTree
from pytrustnfe.xml.DynamicXml import DynamicXml, gerar_xml
class test_xml_serializacao(unittest.TestCase):
def test_serializacao(self):
t = DynamicXml("enviNFe")
t(versao="3.10")
t.idLote = "1"
t.indSinc = "1"
t.NFe.infNFe(versao="3.10", Id="NFe456465465465465654652123564878")
t.NFe.infNFe.ide.cUF = "32"
t.NFe.infNFe.ide.cNF = "0001"
t.NFe.infNFe.ide.natOp = "Venda de mercadorias"
print("Iniciando a geração do xml")
print str(t)
root = Element(str(t))
gerar_xml(root, t)
print(dir(t))
tree = ElementTree(root)
tree.write("/home/danimar/Desktop/nfe.xml")

67
pytrustnfe/xml/DynamicXml.py

@ -0,0 +1,67 @@
'''
Created on Jun 17, 2015
@author: danimar
'''
import xml.etree.ElementTree as ET
from collections import OrderedDict
class DynamicXml(object):
def __getattr__(self, name):
try:
return object.__getattribute__(self,name)
except:
self.__setattr__(name, None)
return object.__getattribute__(self,name)
def __setattr__(self, obj, val):
if(obj=="value" or obj=="atributos"):
object.__setattr__(self,obj, val)
else:
object.__setattr__(self,obj, DynamicXml(val))
def __init__(self, value):
self.value = value
self.atributos={}
object.__setattr__(self, '__dict__', OrderedDict())
def __str__(self):
return str(self.value)
def __call__(self, *args, **kw):
if(len(kw)>0):
self.atributos=kw
if(len(args)>0):
self.value= args[0]
else:
return self.value
def __getitem__(self, i):
print(self.value)
if(i >= len(self.value)):
self.value.append(DynamicXml(None))
return self.value[i]
def gerar_xml(xml, objeto):
for attr, value in objeto.__dict__.items():
if(attr!="value" and attr!="atributos"):
if(type(value()) == type([])):
for item in value():
print(item)
gerar_xml(xml, item)
else:
sub = ET.SubElement(xml,attr)
if(str(value)!="None"):
sub.text = str(value)
gerar_xml(sub, value)
elif(attr=="atributos"):
for atr, val in value.items():
xml.set(atr.replace("__", ":"), str(val))

0
pytrustnfe/xml/__init__.py

Loading…
Cancel
Save