Browse Source

Refatorando código

tags/0.1.5
Danimar Ribeiro 10 years ago
parent
commit
79a9339340
  1. 9
      pytrustnfe/Certificado.py
  2. 6
      pytrustnfe/HttpClient.py
  3. 26
      pytrustnfe/servicos/Assinatura.py
  4. 34
      pytrustnfe/servicos/Comunicacao.py
  5. 6
      pytrustnfe/servicos/nfe_autorizacao.py
  6. 7
      setup.py

9
pytrustnfe/Certificado.py

@ -15,10 +15,13 @@ def converte_pfx_pem(caminho, senha):
try:
certificado = crypto.load_pkcs12(stream, senha)
privada = crypto.dump_privatekey(crypto.FILETYPE_PEM, certificado.get_privatekey())
certificado = crypto.dump_certificate(crypto.FILETYPE_PEM, certificado.get_certificate())
privada = crypto.dump_privatekey(crypto.FILETYPE_PEM,
certificado.get_privatekey())
certificado = crypto.dump_certificate(crypto.FILETYPE_PEM,
certificado.get_certificate())
except Exception as e:
if len(e.message) == 1 and len(e.message[0])==3 and e.message[0][2] == 'mac verify failure':
if len(e.message) == 1 and len(e.message[0]) == 3 and \
e.message[0][2] == 'mac verify failure':
raise Exception('Senha inválida')
raise
return privada, certificado

6
pytrustnfe/HttpClient.py

@ -6,6 +6,7 @@ Created on Jun 16, 2015
'''
from httplib import HTTPSConnection
class HttpClient(object):
def __init__(self, url, chave_pem, certificado_pem):
@ -31,9 +32,6 @@ class HttpClient(object):
return response.read()
return response.read()
except Exception as e:
print str(e)
print(str(e))
finally:
conexao.close()

26
pytrustnfe/servicos/Assinatura.py

@ -39,14 +39,16 @@ class Assinatura(object):
self._checar_certificado()
self._inicializar_cripto()
try:
doc_xml = libxml2.parseMemory(xml.encode('utf-8'), len(xml.encode('utf-8')))
doc_xml = libxml2.parseMemory(xml.encode('utf-8'),
len(xml.encode('utf-8')))
signNode = xmlsec.TmplSignature(doc_xml, xmlsec.transformInclC14NId(),
signNode = xmlsec.TmplSignature(doc_xml,
xmlsec.transformInclC14NId(),
xmlsec.transformRsaSha1Id(), None)
doc_xml.getRootElement().addChild(signNode)
refNode = signNode.addReference(xmlsec.transformSha1Id(),
refNode = signNode.addReference(
xmlsec.transformSha1Id(),
None, '#NFe43150602261542000143550010000000761792265342', None)
refNode.addTransform(xmlsec.transformEnvelopedId())
@ -55,7 +57,9 @@ class Assinatura(object):
keyInfoNode.addX509Data()
dsig_ctx = xmlsec.DSigCtx()
chave = xmlsec.cryptoAppKeyLoad(filename=str(self.arquivo), format=xmlsec.KeyDataFormatPkcs12,
chave = xmlsec.cryptoAppKeyLoad(
filename=str(self.arquivo),
format=xmlsec.KeyDataFormatPkcs12,
pwd=str(self.senha), pwdCallback=None, pwdCallbackCtx=None)
dsig_ctx.signKey = chave
@ -65,14 +69,16 @@ class Assinatura(object):
dsig_ctx.destroy()
if status != xmlsec.DSigStatusSucceeded:
raise RuntimeError('Erro ao realizar a assinatura do arquivo; status: "' + str(status) + '"')
raise RuntimeError(
'Erro ao realizar a assinatura do arquivo; status: "' +
str(status) + '"')
xpath = doc_xml.xpathNewContext()
xpath.xpathRegisterNs('sig', NAMESPACE_SIG)
certificados = xpath.xpathEval('//sig:X509Data/sig:X509Certificate')
for i in range(len(certificados)-1):
certificados[i].unlinkNode()
certificados[i].freeNode()
certs = xpath.xpathEval('//sig:X509Data/sig:X509Certificate')
for i in range(len(certs)-1):
certs[i].unlinkNode()
certs[i].freeNode()
xml = doc_xml.serialize()
return xml

34
pytrustnfe/servicos/Comunicacao.py

@ -7,15 +7,12 @@ Created on Jun 14, 2015
from lxml import objectify
from uuid import uuid4
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import tostring
from pytrustnfe.xml.DynamicXml import DynamicXml
from pytrustnfe.HttpClient import HttpClient
from pytrustnfe.Certificado import converte_pfx_pem
from xml.dom.minidom import parseString
from pytrustnfe.Strings import CONSULTA_CADASTRO_COMPLETA
common_namespaces = {'soap': 'http://www.w3.org/2003/05/soap-envelope'}
soap_body_path = './soap:Envelope/soap:Body'
@ -33,18 +30,18 @@ class Comunicacao(object):
self.senha = senha
def _soap_xml(self, body):
return '<?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/' + self.metodo + '">'\
'<cUF>42</cUF><versaoDados>2.00</versaoDados>'\
'</nfeCabecMsg>'\
'</soap:Header>'\
'<soap:Body>'\
'<nfeDadosMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/' + self.metodo + '">'\
+ body + '</nfeDadosMsg>'\
'</soap:Body>'\
'</soap:Envelope>'
xml = '''<?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/'''
xml += self.metodo
xml += '''"><cUF>42</cUF><versaoDados>2.00</versaoDados>
</nfeCabecMsg>
</soap:Header>
<soap:Body>
<nfeDadosMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/'''
xml += self.metodo + '">' + body
xml += '</nfeDadosMsg></soap:Body></soap:Envelope>'
def _preparar_temp_pem(self):
chave_temp = '/tmp/' + uuid4().hex
@ -86,7 +83,6 @@ class Comunicacao(object):
soap_xml = self._soap_xml(xmlEnviar)
xml_retorno = client.post_xml(self.web_service, soap_xml)
dom = parseString(xml_retorno)
nodes = dom.getElementsByTagNameNS(common_namespaces['soap'], 'Fault')
if len(nodes) > 0:
@ -98,7 +94,3 @@ class Comunicacao(object):
return nodes[0].toxml(), obj
return xml_retorno, objectify.fromstring(xml_retorno)

6
pytrustnfe/servicos/NFeAutorizacao.py → pytrustnfe/servicos/nfe_autorizacao.py

@ -5,7 +5,6 @@ Created on 21/06/2015
@author: danimar
'''
from pytrustnfe.servicos.Comunicacao import Comunicacao
from pytrustnfe.xml import DynamicXml
from pytrustnfe import utils
@ -42,7 +41,4 @@ class NfeAutorizacao(Comunicacao):
self.web_service = 'ws/NfeRetAutorizacao/NFeRetAutorizacao.asmx'
self.url = 'nfe.sefazrs.rs.gov.br'
return self._executar_consulta(xml)
return self._executar_consulta(xml), consulta_recibo

7
setup.py

@ -11,7 +11,8 @@ setup(
'Development Status :: 1 - alpha',
'Environment :: Plugins',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)',
'License :: OSI Approved :: GNU Lesser General Public License v2 or \
later (LGPLv2+)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
@ -22,7 +23,9 @@ setup(
description='PyNfeTrust é uma biblioteca para envio de NF-e',
long_description='PyNfeTrust',
install_requires=[
'PyXMLSec >= 0.3.0'
'PyXMLSec >= 0.3.0',
'Jinja2 >= 2.8',
'signxml >= 1.0.0',
],
test_suite='nose.collector',
tests_require=[

Loading…
Cancel
Save