-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
194 lines (148 loc) · 6.48 KB
/
app.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
# -*- coding: utf-8 -*-
import json
import gzip
import os
import logging
from datetime import datetime
from chalice import Chalice, Response, BadRequestError
from chalicelib.model import DataRepository
# load environment variables
config = {
"MONGODB_URI": os.environ.get("MONGODB_URI", "mongodb://localhost:27017"),
"DB_NAME" : os.environ.get("DB_NAME", "meuParlamento")
}
# setup rest api app
app = Chalice(app_name='meuparlamento-backend-api')
app.api.binary_types.append('application/json')
app.log.setLevel(logging.DEBUG)
# setup data connections
data_repo = DataRepository(config)
data_repo.connect()
@app.route('/')
def index():
"""
Test endpoint.
Just to make sure it is running.
"""
return {'hello': 'meuParlamento!'}
@app.route('/register_device', methods=["POST"])
def register_device():
"""
Register unique id in order to send notifications.
"""
app.log.debug("register nofitication device")
try:
# read request body
request_body = app.current_request.json_body
if(request_body):
data_repo.register_device(request_body['token'])
return Response(status_code=201,
body={"message":"Device registered for notification"},
headers={'Content-Type': 'application/json'})
except Exception as e:
app.log.error("failed to register notification device")
raise BadRequestError('Failed to register device. Unable to support notifications for this device')
@app.route('/proposals/agenda/today')
def show_agenda_today():
return show_agenda_at(datetime.now())
@app.route('/proposals/agenda/at/{date_agenda}')
def show_agenda_at(date_agenda):
"""Return agenda for the day
"""
try:
date_agenda = datetime.strptime(date_agenda,'%Y%m%d')
except:
date_agenda = datetime.now()
app.log.debug("get agenda {}".format(date_agenda))
try:
# generate recent sampling
my_batch = data_repo.show_agenda(date_agenda)
response = json.dumps({"data":my_batch}).encode('utf-8')
payload = gzip.compress(response)
return Response(status_code=200,
body=payload,
headers={'Content-Type': 'application/json',
'Content-Encoding': 'gzip'})
except Exception as e:
app.log.error("failed to get proposals batch")
raise BadRequestError('Oops. Something bad happened :( If error persists, please contact system admin')
@app.route('/proposals/recent/{batch_size}')
def generate_proposals_recent(batch_size):
"""Return a batch with recent proposals
:batch_size: An integer, max number of proposals to return
"""
app.log.debug("get recent proposals batch. size {}".format(batch_size))
try:
# generate recent sampling
my_batch = data_repo.recent_batch(int(batch_size))
response = json.dumps({"data":my_batch}).encode('utf-8')
payload = gzip.compress(response)
return Response(status_code=200,
body=payload,
headers={'Content-Type': 'application/json',
'Content-Encoding': 'gzip'})
except Exception as e:
app.log.error("failed to get proposals batch")
raise BadRequestError('Oops. Something bad happened :( If error persists, please contact system admin')
@app.route('/proposals/batch/{batch_size}')
def generate_proposals_sampling(batch_size):
"""Return a batch with random proposals
:batch_size: An integer, max number of proposals to return
"""
app.log.debug("get random proposals batch. size {}".format(batch_size))
try:
# generate sampling
my_batch = data_repo.sampling_batch(int(batch_size))
response = json.dumps({"data":my_batch}).encode('utf-8')
payload = gzip.compress(response)
return Response(status_code=200,
body=payload,
headers={'Content-Type': 'application/json',
'Content-Encoding': 'gzip'})
except Exception as e:
app.log.error("failed to get proposals batch")
raise BadRequestError('Oops. Something bad happened :( If error persists, please contact system admin')
@app.route('/proposals/authors/{proposalID}')
def authors_from_proposal(proposalID):
"""Return authors from proposal
:proposalID: An integer, proposal's identifier
"""
app.log.debug("authors_from_proposal: {}".format(proposalID))
try:
authors = data_repo.find_authors_by_proposal_id(proposalID)
response = json.dumps({"data":authors}).encode('utf-8')
payload = gzip.compress(response)
return Response(status_code=200,
body=payload,
headers={'Content-Type': 'application/json',
'Content-Encoding': 'gzip'})
except Exception as e:
app.log.error("failed to get authors from proposal {}".format(proposalID))
raise BadRequestError('Oops. Something bad happened :( If error persists, please contact system admin')
@app.route('/proposals/news/{proposalID}')
def news_search(proposalID):
"""Return a list with related news websites
:proposalID: An integer, proposal's identifier
"""
proposal = data_repo.find_proposal_by_id(proposalID)
if(proposal):
voteDate = datetime.fromtimestamp(proposal["dataVotacao"]/1000).strftime("%Y-%m-%d")
return _news_search(proposalID, voteDate)
@app.route('/proposals/news/{proposalID}/{proposalDate}')
def _news_search(proposalID, proposalDate):
"""Return a list with related news websites
:proposalID: An integer, proposal's identifier
:proposalDate: proposal's vote date. Format "YYYY-mm-dd"
"""
app.log.debug("news_search: {}".format(proposalID))
try:
hits = data_repo.news_search(proposalID, proposalDate)
response = json.dumps({"data":hits}).encode('utf-8')
payload = gzip.compress(response)
return Response(status_code=200,
body=payload,
headers={'Content-Type': 'application/json',
'Content-Encoding': 'gzip'})
except Exception as e:
app.log.error("failed to search news from proposal id {} at {}".format(proposalID, proposalDate))
raise BadRequestError('Oops. Something bad happened :( If error persists, please contact system admin')