forked from PostmonAPI/postmon
/
PostmonServer.py
217 lines (174 loc) · 6.2 KB
/
PostmonServer.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import bottle
import json
import logging
import xmltodict
from bottle import run, request, response, template, HTTPResponse
from bottle.ext.healthcheck import HealthCheck
from raven import Client
from raven.contrib.bottle import Sentry
from CepTracker import CepTracker
import PackTracker
import requests
from database import MongoDb as Database
logger = logging.getLogger(__name__)
HealthCheck(bottle, "/__health__")
app = bottle.default_app()
app.catchall = False
app_v1 = bottle.Bottle()
app_v1.catchall = False
jsonp_query_key = 'callback'
def validate_format(callback):
def wrapper(*args, **kwargs):
output_format = request.query.format
if output_format and output_format not in {'json', 'jsonp', 'xml'}:
message = "400 Parametro format='%s' invalido." % output_format
return make_error(message, output_format='json')
return callback(*args, **kwargs)
return wrapper
def expired(record_date):
if 'v_date' not in record_date:
return True
from datetime import datetime, timedelta
# 6 months
WEEKS = 26
now = datetime.now()
return (now - record_date['v_date'] >= timedelta(weeks=WEEKS))
def _get_info_from_source(cep):
tracker = CepTracker()
return tracker.track(cep)
def format_result(result):
# checa se foi solicitada resposta em JSONP
js_func_name = bottle.request.query.get(jsonp_query_key)
# checa se foi solicitado xml
format = bottle.request.query.get('format')
if format == 'xml':
response.content_type = 'application/xml'
return xmltodict.unparse({'result': result})
if js_func_name:
# se a resposta vai ser JSONP, o content type deve ser js e seu
# conteudo deve ser JSON
response.content_type = 'application/javascript'
result = json.dumps(result)
result = '%s(%s);' % (js_func_name, result)
return result
def make_error(message, output_format=None):
formats = {
'json': 'application/json',
'xml': 'application/xml',
'jsonp': 'application/javascript',
}
format_ = output_format or bottle.request.query.get('format', 'json')
response = HTTPResponse(status=message, content_type=formats[format_])
response.headers['Access-Control-Allow-Origin'] = '*'
return response
def _get_estado_info(db, sigla):
sigla = sigla.upper()
return db.get_one_uf(sigla, fields={'_id': False, 'sigla': False})
def _get_cidade_info(db, sigla_uf, nome_cidade):
sigla_uf = sigla_uf.upper()
nome_cidade = nome_cidade.upper()
sigla_uf_nome_cidade = '%s_%s' % (sigla_uf, nome_cidade)
fields = {
'_id': False,
'sigla_uf': False,
'codigo_ibge_uf': False,
'sigla_uf_nome_cidade': False,
'nome': False
}
return db.get_one_cidade(sigla_uf_nome_cidade, fields=fields)
@app.route('/cep/<cep:re:\d{5}-?\d{3}>')
@app_v1.route('/cep/<cep:re:\d{5}-?\d{3}>')
def verifica_cep(cep):
cep = cep.replace('-', '')
db = Database()
response.headers['Access-Control-Allow-Origin'] = '*'
message = None
result = db.get_one(cep, fields={'_id': False})
if not result or expired(result):
result = None
try:
info = _get_info_from_source(cep)
except requests.exceptions.RequestException:
message = '503 Servico Temporariamente Indisponivel'
logger.exception(message)
return make_error(message)
else:
for item in info:
db.insert_or_update(item)
result = db.get_one(cep, fields={'_id': False, 'v_date': False})
if not result or '__notfound__' in result:
message = '404 CEP %s nao encontrado' % cep
return make_error(message)
result.pop('v_date', None)
response.headers['Cache-Control'] = 'public, max-age=2592000'
sigla_uf = result['estado']
estado_info = _get_estado_info(db, sigla_uf)
if estado_info:
result['estado_info'] = estado_info
nome_cidade = result['cidade']
cidade_info = _get_cidade_info(db, sigla_uf, nome_cidade)
if cidade_info:
result['cidade_info'] = cidade_info
return format_result(result)
@app_v1.route('/uf/<sigla>')
def uf(sigla):
response.headers['Access-Control-Allow-Origin'] = '*'
db = Database()
result = _get_estado_info(db, sigla)
if result:
response.headers['Cache-Control'] = 'public, max-age=2592000'
return format_result(result)
else:
message = '404 Estado %s nao encontrado' % sigla
logger.warning(message)
return make_error(message)
@app_v1.route('/cidade/<sigla_uf>/<nome>')
def cidade(sigla_uf, nome):
response.headers['Access-Control-Allow-Origin'] = '*'
db = Database()
result = _get_cidade_info(db, sigla_uf, nome)
if result:
response.headers['Cache-Control'] = 'public, max-age=2592000'
return format_result(result)
else:
message = '404 Cidade %s-%s nao encontrada' % (nome, sigla_uf)
logger.warning(message)
return make_error(message)
@app_v1.route('/rastreio/<provider>/<track>')
def track_pack(provider, track):
response.headers['Access-Control-Allow-Origin'] = '*'
if provider == 'ect':
try:
historico = PackTracker.correios(track)
except (AttributeError, ValueError):
message = "404 Pacote %s nao encontrado" % track
logger.exception(message)
else:
return format_result({
'servico': provider,
'codigo': track,
'historico': historico,
})
else:
message = '404 Servico %s nao encontrado' % provider
logger.warning(message)
return make_error(message)
@app.route('/crossdomain.xml')
def crossdomain():
response.content_type = 'application/xml'
return template('crossdomain')
app.install(validate_format)
app_v1.install(validate_format)
app.mount('/v1', app_v1)
SENTRY_DSN = os.getenv('SENTRY_DSN')
if SENTRY_DSN:
sentry_client = Client(SENTRY_DSN)
app = Sentry(app, sentry_client)
app_v1 = Sentry(app_v1, sentry_client)
def _standalone(port=9876):
run(app=app, host='0.0.0.0', port=port)
if __name__ == "__main__":
_standalone()