|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
1 | 3 | import bottle |
2 | 4 | import json |
3 | 5 | from bottle import route, run, response |
|
6 | 8 | from correios import Correios |
7 | 9 | from database import MongoDb as Database |
8 | 10 |
|
| 11 | + |
9 | 12 | app_v1 = bottle.Bottle() |
10 | 13 | jsonp_query_key = 'callback' |
11 | 14 |
|
| 15 | + |
12 | 16 | def expired(record_date): |
13 | | - from datetime import datetime, timedelta |
| 17 | + from datetime import datetime, timedelta |
14 | 18 |
|
15 | | - WEEKS = 26 #6 months |
| 19 | + # 6 months |
| 20 | + WEEKS = 26 |
16 | 21 |
|
17 | | - now = datetime.now() |
| 22 | + now = datetime.now() |
18 | 23 |
|
19 | | - return ( now - record_date['v_date'] >= timedelta(weeks=WEEKS)) |
| 24 | + return (now - record_date['v_date'] >= timedelta(weeks=WEEKS)) |
20 | 25 |
|
21 | 26 |
|
22 | 27 | def _get_info_from_source(cep): |
23 | | - tracker = CepTracker() |
24 | | - info = tracker.track(cep) |
25 | | - if len(info) == 0: |
26 | | - raise ValueError() |
27 | | - return info |
| 28 | + tracker = CepTracker() |
| 29 | + info = tracker.track(cep) |
| 30 | + if len(info) == 0: |
| 31 | + raise ValueError() |
| 32 | + return info |
28 | 33 |
|
29 | 34 |
|
30 | 35 | def format_result(result): |
31 | | - # checa se foi solicitada resposta em JSONP |
32 | | - js_func_name = bottle.request.query.get(jsonp_query_key) |
| 36 | + # checa se foi solicitada resposta em JSONP |
| 37 | + js_func_name = bottle.request.query.get(jsonp_query_key) |
33 | 38 |
|
34 | | - if js_func_name: |
35 | | - # se a resposta vai ser JSONP, o content type deve ser js e seu |
36 | | - # conteudo deve ser JSON |
37 | | - response.content_type = 'application/javascript' |
38 | | - result = json.dumps(result) |
| 39 | + if js_func_name: |
| 40 | + # se a resposta vai ser JSONP, o content type deve ser js e seu |
| 41 | + # conteudo deve ser JSON |
| 42 | + response.content_type = 'application/javascript' |
| 43 | + result = json.dumps(result) |
39 | 44 |
|
40 | | - result = '%s(%s);' % (js_func_name, result) |
41 | | - return result |
| 45 | + result = '%s(%s);' % (js_func_name, result) |
| 46 | + return result |
42 | 47 |
|
43 | 48 |
|
44 | 49 | @route('/cep/<cep:re:\d{5}-?\d{3}>') |
45 | 50 | @app_v1.route('/cep/<cep:re:\d{5}-?\d{3}>') |
46 | 51 | def verifica_cep(cep): |
47 | | - cep = cep.replace('-','') |
48 | | - db = Database() |
49 | | - response.headers['Access-Control-Allow-Origin'] = '*' |
50 | | - |
51 | | - result = db.get_one(cep, fields={ '_id': False }) |
52 | | - if result and result.has_key('v_date') and not expired(result): |
53 | | - result.pop('v_date') |
54 | | - else: |
55 | | - try: |
56 | | - info = _get_info_from_source(cep) |
57 | | - except ValueError: |
58 | | - response.status = '404 O CEP %s informado nao pode ser localizado' % cep |
59 | | - return |
60 | | - except requests.exceptions.RequestException: |
61 | | - response.status = '503 Servico Temporariamente Indisponivel' |
62 | | - return |
63 | | - for item in info: |
64 | | - db.insert_or_update(item) |
65 | | - result = db.get_one(cep, fields={ '_id': False, 'v_date': False }) |
66 | | - |
67 | | - if result: |
68 | | - |
69 | | - response.headers['Cache-Control'] = 'public, max-age=2592000' |
70 | | - return format_result(result) |
71 | | - else: |
72 | | - response.status = '404 O CEP %s informado nao pode ser localizado' % cep |
73 | | - return |
| 52 | + cep = cep.replace('-', '') |
| 53 | + db = Database() |
| 54 | + response.headers['Access-Control-Allow-Origin'] = '*' |
| 55 | + |
| 56 | + result = db.get_one(cep, fields={'_id': False}) |
| 57 | + if result and 'v_date' in result and not expired(result): |
| 58 | + result.pop('v_date') |
| 59 | + else: |
| 60 | + try: |
| 61 | + info = _get_info_from_source(cep) |
| 62 | + except ValueError: |
| 63 | + response.status = "404 O CEP {0} informado nao pode ser " |
| 64 | + "localizado".format(cep) |
| 65 | + return |
| 66 | + except requests.exceptions.RequestException: |
| 67 | + response.status = '503 Servico Temporariamente Indisponivel' |
| 68 | + return |
| 69 | + for item in info: |
| 70 | + db.insert_or_update(item) |
| 71 | + result = db.get_one(cep, fields={'_id': False, 'v_date': False}) |
| 72 | + |
| 73 | + if result: |
| 74 | + |
| 75 | + response.headers['Cache-Control'] = 'public, max-age=2592000' |
| 76 | + return format_result(result) |
| 77 | + else: |
| 78 | + response.status = '404 O CEP %s informado nao pode ser ' |
| 79 | + 'localizado' % cep |
| 80 | + return |
74 | 81 |
|
75 | 82 |
|
76 | 83 | @app_v1.route('/rastreio/<provider>/<track>') |
77 | 84 | def track_pack(provider, track): |
78 | | - if provider == 'ect': |
79 | | - try: |
80 | | - encomenda = Correios.encomenda(track) |
| 85 | + if provider == 'ect': |
| 86 | + try: |
| 87 | + encomenda = Correios.encomenda(track) |
81 | 88 |
|
82 | | - resposta = dict() |
83 | | - result = [] |
| 89 | + resposta = dict() |
| 90 | + result = [] |
84 | 91 |
|
85 | | - for status in encomenda.status: |
86 | | - historico = dict() |
87 | | - |
88 | | - historico['data'] = status.data |
89 | | - historico['local'] = status.local |
90 | | - historico['situacao'] = status.situacao |
91 | | - historico['detalhes'] = status.detalhes |
| 92 | + for status in encomenda.status: |
| 93 | + historico = dict() |
| 94 | + historico['data'] = status.data |
| 95 | + historico['local'] = status.local |
| 96 | + historico['situacao'] = status.situacao |
| 97 | + historico['detalhes'] = status.detalhes |
92 | 98 |
|
93 | | - result.append(historico) |
| 99 | + result.append(historico) |
94 | 100 |
|
95 | | - resposta['servico'] = provider |
96 | | - resposta['codigo'] = track |
97 | | - resposta['historico'] = result |
| 101 | + resposta['servico'] = provider |
| 102 | + resposta['codigo'] = track |
| 103 | + resposta['historico'] = result |
98 | 104 |
|
99 | | - return format_result(resposta) |
| 105 | + return format_result(resposta) |
| 106 | + |
| 107 | + except AttributeError: |
| 108 | + response.status = "404 O pacote {0} informado nao pode ser " |
| 109 | + "localizado".format(track) |
| 110 | + else: |
| 111 | + response.status = '404 O Servico %s nao pode ser encontrado' % provider |
100 | 112 |
|
101 | | - except AttributeError: |
102 | | - response.status = '404 O pacote %s informado nao pode ser localizado' %track |
103 | | - else: |
104 | | - response.status = '404 O Servico %s nao pode ser encontrado' %provider |
105 | 113 |
|
106 | 114 | bottle.mount('/v1', app_v1) |
107 | 115 |
|
| 116 | + |
108 | 117 | def _standalone(port=9876): |
109 | 118 | run(host='localhost', port=port) |
0 commit comments