Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python 3 #22

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions pycorreios/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import correios
from correios import *
from . import correios
from .correios import *

# __all__ = (correios.__all__ + cod.__all__)

Expand Down
76 changes: 57 additions & 19 deletions pycorreios/correios.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,29 @@
Api para usar dados dos Correios
"""

__version__ = '0.1.0'
__version__ = '0.2.0'
__author__ = {
'Thiago Avelino': 'thiagoavelinoster@gmail.com',
'Dilan Nery': 'dnerylopes@gmail.com',
}

import urllib
import urllib2
import sys

python_version = sys.version_info[0]
from six.moves import urllib
import re

from xml.dom import minidom

try:
from BeautifulSoup import BeautifulSoup
from bs4 import BeautifulSoup


except ImportError:
raise Exception('Você não tem o modulo BeautifulSoup', ImportError)
try:
from BeautifulSoup import BeautifulSoup
except ImportError:
raise Exception('Você não tem o modulo BeautifulSoup', ImportError)


class Correios(object):
Expand Down Expand Up @@ -76,8 +84,8 @@ def frete(self, cod, GOCEP, HERECEP, peso, formato,
('StrRetorno', toback),
]

url = base_url + "?" + urllib.urlencode(fields)
dom = minidom.parse(urllib2.urlopen(url))
url = base_url + "?" + urllib.parse.urlencode(fields)
dom = minidom.parse(urllib.request.urlopen(url))

tags_name = ('MsgErro',
'Erro',
Expand All @@ -87,14 +95,20 @@ def frete(self, cod, GOCEP, HERECEP, peso, formato,
'ValorMaoPropria',
'ValorValorDeclarado',
'EntregaDomiciliar',
'EntregaSabado',)
'EntregaSabado',)

# consulta de mais de um servico simultaneamente
qtd_servicos = len(str(cod).split(','))

if (qtd_servicos > 1):
return self._dom_to_object(dom.firstChild)

return self._getDados(tags_name, dom)

def cep(self, numero):
url = 'http://cep.republicavirtual.com.br/web_cep.php?formato=' \
'xml&cep=%s' % str(numero)
dom = minidom.parse(urllib2.urlopen(url))
dom = minidom.parse(urllib.request.urlopen(url))

tags_name = ('uf',
'cidade',
Expand All @@ -108,6 +122,8 @@ def cep(self, numero):
return self._getDados(tags_name, dom)
else:
return {}



def encomenda(self, numero):
# Usado como referencia o codigo do Guilherme Chapiewski
Expand All @@ -117,25 +133,47 @@ def encomenda(self, numero):
'P_ITEMCODE=&P_LINGUA=001&P_TESTE=&P_TIPO=001&P_COD_UNI=%s' % \
str(numero)

html = urllib2.urlopen(url).read()
table = re.search(r'<table.*</TABLE>', html, re.S).group(0)
html = urllib.request.urlopen(url).read()

table = re.search(b'<table.*</TABLE>', html, re.S).group(0)

parsed = BeautifulSoup(table)
parsed = BeautifulSoup(table, "html.parser")

dados = []

for count, tr in enumerate(parsed.table):
if count > 4 and str(tr).strip() != '':
for count, tr in enumerate(parsed.findAll('tr')):
if count > 0 and str(tr).strip() != '':
if re.match(r'\d{2}/\d{2}/\d{4} \d{2}:\d{2}',
tr.contents[0].string):

dados.append({
'data': unicode(tr.contents[0].string),
'local': unicode(tr.contents[1].string),
'status': unicode(tr.contents[2].font.string)
'data': tr.contents[0].string,
'local': tr.contents[1].string,
'status': tr.contents[2].font.string
})

else:
dados[len(dados) - 1]['detalhes'] = unicode(
tr.contents[0].string)
dados[len(dados) - 1]['detalhes'] = tr.contents[0].string

return dados


def _dom_to_object(self, dom):
result ={}
child_tags = [child for child in dom.childNodes if isinstance(child,minidom.Element)]
if not child_tags:
content = ''.join(txt.data.strip() for txt in dom.childNodes if isinstance(txt,minidom.Text))
return content
else:
tags = set([tag.tagName for tag in child_tags])
for tagName in tags:
elements = dom.getElementsByTagName(tagName)
if len(elements) > 1:
content = []
for e in elements:
content.append(self._dom_to_object(e))
result[dom.tagName] = content
else:
content = self._dom_to_object(elements[0])
result[tagName]=content
return result
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ def get_version(version_tuple):
# Dirty hack to get version number from pycorreios/__init__.py - we can't
# file is read
init = os.path.join(os.path.dirname(__file__), 'pycorreios', '__init__.py')
version_line = filter(lambda l: l.startswith('VERSION'), open(init))[0]
version_line = list(filter(lambda l: l.startswith('VERSION'), open(init)))[0]
VERSION = get_version(eval(version_line.split('=')[-1]))
print VERSION
print(VERSION)

CLASSIFIERS = [
'Development Status :: 4 - Beta',
Expand Down
52 changes: 23 additions & 29 deletions test/correios_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,49 +2,43 @@
# -*- coding: utf-8 -*-

import unittest
from unittest import main
from pycorreios.correios import Correios


class CorreiosTest(unittest.TestCase):

def test_frete(self):

valor_esperado = {
'MsgErro': '',
'PrazoEntrega': u'2',
'Erro': u'0',
'ValorValorDeclarado': u'0,00',
'EntregaDomiciliar': u'S',
'ValorMaoPropria': u'0,00',
'EntregaSabado': u'S',
'Valor': u'62,40',
'Codigo': u'40010'
}
valor = Correios().frete(Correios.SEDEX, '44001535', '03971010',

result = Correios().frete(Correios.SEDEX, '09840240', '09820650',
1, 1, 18, 9, 13.5, 0)
valor = float(result['Valor'].replace(',','.'))
self.assertTrue(not result['MsgErro'])
self.assertTrue(valor > 0)


def test_frete_servicos(self):
servicos = ','.join(str(i) for i in [Correios.SEDEX, Correios.PAC])
result = Correios().frete(servicos, '09840240', '09820650',
1, 1, 18, 9, 13.5, 0)
results = result['Servicos']
self.assertTrue(len(results)>1)
for servico in results:
self.assertTrue(not servico['MsgErro'])

self.assertDictEqual(valor_esperado, valor)

def test_cep(self):

valor_esperado = {
'tipo_logradouro': u'Rua',
'bairro': u'Jardim Santa Adelia',
'cidade': u'S\xe3o Paulo',
'uf': u'SP',
'logradouro': u'Pascoal Dias',
}
keys = ['tipo_logradouro','bairro','cidade','uf','logradouro']

valor = Correios().cep('03971010')
self.assertDictEqual(valor_esperado, valor)
self.assertEqual(set(keys), set(valor.keys()))


def test_encomenda(self):
valor = Correios().encomenda('PN569489984BR')[0]
self.assertEqual(valor['status'], 'Entrega Efetuada')

valor_esperado = {
'data': '03/02/2016 17:57',
'local': u'CDD ITAJUBA - Itajuba/MG',
'status': 'Entrega Efetuada',
}

valor = Correios().encomenda('PJ382325976BR')[0]
self.assertDictEqual(valor_esperado, valor)
if __name__ == '__main__':
main()