|
| 1 | +# coding: utf-8 |
| 2 | +import requests |
| 3 | + |
| 4 | +BASE_URL = 'http://api.postmon.com.br/v1' |
| 5 | + |
| 6 | + |
| 7 | +class Cidade(object): |
| 8 | + |
| 9 | + def __init__(self, nome, area_km2=None, codigo_ibge=None): |
| 10 | + self.nome = nome |
| 11 | + self.area_km2 = area_km2 |
| 12 | + self.codigo_ibge = codigo_ibge |
| 13 | + |
| 14 | + def __repr__(self): |
| 15 | + return '<postmon.Cidade %r>' % self.nome |
| 16 | + |
| 17 | + def __str__(self): |
| 18 | + return self.nome |
| 19 | + |
| 20 | + |
| 21 | +class Estado(object): |
| 22 | + |
| 23 | + def __init__(self, uf, nome=None, area_km2=None, codigo_ibge=None): |
| 24 | + self.uf = uf |
| 25 | + self.nome = nome |
| 26 | + self.area_km2 = area_km2 |
| 27 | + self.codigo_ibge = codigo_ibge |
| 28 | + |
| 29 | + def __repr__(self): |
| 30 | + return '<postmon.Estado %r>' % self.uf |
| 31 | + |
| 32 | + def __str__(self): |
| 33 | + return self.uf |
| 34 | + |
| 35 | + |
| 36 | +class Endereco(object): |
| 37 | + |
| 38 | + def __init__(self, **kwargs): |
| 39 | + self.cep = kwargs['cep'] |
| 40 | + self.logradouro = kwargs.get('logradouro') |
| 41 | + self.bairro = kwargs.get('bairro') |
| 42 | + |
| 43 | + estado_info = kwargs.get('estado_info', {}) |
| 44 | + self.estado = Estado(kwargs['estado'], |
| 45 | + estado_info.get('nome'), |
| 46 | + estado_info.get('area_km2'), |
| 47 | + estado_info.get('codigo_ibge')) |
| 48 | + |
| 49 | + cidade_info = kwargs.get('cidade_info', {}) |
| 50 | + self.cidade = Cidade(kwargs['cidade'], |
| 51 | + cidade_info.get('area_km2'), |
| 52 | + cidade_info.get('codigo_ibge')) |
| 53 | + |
| 54 | + def __repr__(self): |
| 55 | + return '<postmon.Endereco %r>' % self.cep |
| 56 | + |
| 57 | + def __str__(self): |
| 58 | + return '%s, %s - %s, %s - CEP: %s' % (self.logradouro, self.bairro, |
| 59 | + self.cidade, self.estado, |
| 60 | + self.cep) |
| 61 | + |
| 62 | + |
| 63 | +def buscar_cep(cep): |
| 64 | + response = _GET('/cep/%s' % cep) |
| 65 | + response.raise_for_status() |
| 66 | + return Endereco(**response.json()) |
| 67 | + |
| 68 | + |
| 69 | +def _GET(endpoint): |
| 70 | + url = '%s%s' % (BASE_URL, endpoint) |
| 71 | + response = requests.get(url) |
| 72 | + return response |
0 commit comments