-
Notifications
You must be signed in to change notification settings - Fork 81
/
CepTracker.py
executable file
·73 lines (62 loc) · 1.97 KB
/
CepTracker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
import logging
import os
import re
import requests
logger = logging.getLogger(__name__)
_notfound_key = '__notfound__'
class CepTracker(object):
url = os.getenv(
"CORREIOS_CEP_URL",
"https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php", # NOQA
)
def _request(self, cep):
response = requests.post(self.url, data={
"pagina": "/app/endereco/index.php",
"cepaux": "",
"mensagem_alerta": "",
"endereco": cep,
"tipoCEP": "ALL",
}, headers={
"Referer": "https://buscacepinter.correios.com.br/app/endereco/index.php?t",
}, timeout=10)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as ex:
logger.exception('Erro no site dos Correios')
raise ex
return response.json()
def track(self, cep):
data = self._request(cep)
result = []
found = False
now = datetime.now()
for item in data["dados"]:
if item['cep'] == cep:
found = True
data = {
"_meta": {
"v_date": now,
},
"cep": item['cep'],
"bairro": item['bairro'],
"cidade": item['localidade'],
"estado": item['uf'],
}
logradouro = item["logradouroDNEC"]
if ' - ' in logradouro:
logradouro, complemento = logradouro.split(' - ', 1)
data['complemento'] = complemento.strip(' -')
data['logradouro'] = logradouro
result.append(data)
if not found:
result.append({
'cep': cep,
'_meta': {
"v_date": now,
_notfound_key: True,
},
})
return result