Skip to content

Commit a105068

Browse files
Add IbgeTracker.py #56
1 parent 574e00c commit a105068

File tree

3 files changed

+122
-1
lines changed

3 files changed

+122
-1
lines changed

IbgeTracker.py

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
import requests
4+
from lxml.html import fromstring
5+
from database import MongoDb as Database
6+
7+
8+
class IbgeTracker():
9+
10+
def __init__(self):
11+
self.url_ufs = 'http://www.ibge.gov.br/home/geociencias' + \
12+
'/areaterritorial/principal.shtm'
13+
self.url_cidades = 'http://www.ibge.gov.br/home/geociencias' + \
14+
'/areaterritorial/area.php?nome=%'
15+
16+
def _request(self, url):
17+
response = requests.post(url)
18+
response.raise_for_status()
19+
return response.text
20+
21+
def _get_info_ufs(self, siglas):
22+
texto = self._request(self.url_ufs)
23+
html = fromstring(texto)
24+
seletorcss_linhas = "div#miolo_interno > table > tr"
25+
linhas = html.cssselect(seletorcss_linhas)
26+
linhas.pop() # a primeira é o cabeçalho
27+
infos = []
28+
for linha in linhas:
29+
seletorcss_celulas = "td"
30+
celulas = linha.cssselect(seletorcss_celulas)
31+
codigo_ibge = celulas[0].text_content()
32+
if codigo_ibge in siglas:
33+
sigla = siglas[codigo_ibge]
34+
infos.append({
35+
'sigla': sigla,
36+
'codigo_ibge': codigo_ibge,
37+
'nome': celulas[1].text_content(),
38+
'area_km2': celulas[2].text_content()
39+
})
40+
41+
# neste ponto, após a carga
42+
# das cidades, a lista
43+
# 'infos' deve estar populada
44+
45+
return infos
46+
47+
def _get_info_cidades(self):
48+
texto = self._request(self.url_cidades)
49+
html = fromstring(texto)
50+
seletorcss_linhas = "div#miolo_interno > table > tr"
51+
linhas = html.cssselect(seletorcss_linhas)
52+
linhas.pop() # a primeira é o cabeçalho
53+
infos = []
54+
for linha in linhas:
55+
seletorcss_celulas = "td"
56+
celulas = linha.cssselect(seletorcss_celulas)
57+
infos.append({
58+
'codigo_ibge_uf': celulas[0].text_content(),
59+
'sigla_uf': celulas[1].text_content(),
60+
'codigo_ibge_cidade': celulas[2].text_content(),
61+
'nome_cidade': celulas[3].text_content(),
62+
'area_km2': celulas[4].text_content()
63+
})
64+
return infos
65+
66+
def _track_ufs(self, db, siglas):
67+
infos = self._get_info_ufs(siglas)
68+
for info in infos:
69+
db.insert_or_update_uf(info)
70+
71+
def _track_cidades(self, db):
72+
infos = self._get_info_cidades()
73+
siglas = {}
74+
for info in infos:
75+
codigo_ibge_uf = info['codigo_ibge_uf']
76+
sigla_uf = info['sigla_uf']
77+
nome_cidade = info['nome_cidade']
78+
if codigo_ibge_uf not in siglas:
79+
siglas[codigo_ibge_uf] = sigla_uf
80+
81+
# a chave única de uma cidade não
82+
# pode ser só o nome, pois
83+
# existem cidades com mesmo nome
84+
# em estados diferentes
85+
info['sigla_uf_nome_cidade'] = '%s_%s' % (sigla_uf, nome_cidade)
86+
87+
db.insert_or_update_cidade(info)
88+
89+
return siglas
90+
91+
def track(self, db):
92+
"""
93+
Atualiza as bases internas do mongo
94+
com os dados mais recentes do IBGE
95+
referente a ufs e cidades
96+
"""
97+
siglas = self._track_cidades(db) # siglas é um dict cod_ibge -> sigla:
98+
# { '35': 'SP', '35': 'RJ', ... }
99+
self._track_ufs(db, siglas)
100+
101+
102+
def _standalone():
103+
db = Database()
104+
ibge = IbgeTracker()
105+
ibge.track(db)
106+
107+
108+
if __name__ == "__main__":
109+
_standalone()

PostmonServer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def format_result(result):
5454

5555

5656
def _get_estado_info(db, sigla):
57-
sigla = sigla.lower()
57+
sigla = sigla.upper()
5858
return db.get_one_uf(sigla, fields={'_id': False, 'sigla': False})
5959

6060

database.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ def get_one(self, cep, **kwargs):
2828
def get_one_uf(self, sigla, **kwargs):
2929
return self._db.ufs.find_one({'sigla': sigla}, **kwargs)
3030

31+
def get_one_uf_by_nome(self, nome, **kwargs):
32+
return self._db.ufs.find_one({'nome': nome}, **kwargs)
33+
3134
def insert_or_update(self, obj, **kwargs):
3235

3336
update = {'$set': obj}
@@ -36,5 +39,14 @@ def insert_or_update(self, obj, **kwargs):
3639

3740
self._db.ceps.update({'cep': obj['cep']}, update, upsert=True)
3841

42+
def insert_or_update_uf(self, obj, **kwargs):
43+
update = {'$set': obj}
44+
self._db.ufs.update({'sigla': obj['sigla']}, update, upsert=True)
45+
46+
def insert_or_update_cidade(self, obj, **kwargs):
47+
update = {'$set': obj}
48+
chave = 'sigla_uf_nome_cidade'
49+
self._db.cidades.update({chave: obj[chave]}, update, upsert=True)
50+
3951
def remove(self, cep):
4052
self._db.ceps.remove({'cep': cep})

0 commit comments

Comments
 (0)