-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
executable file
·257 lines (199 loc) · 7.22 KB
/
main.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import json
import logging
import os
import time
import webapp2
import urllib
from google.cloud import pubsub
from collections import OrderedDict
from google.cloud import bigquery
from google.appengine.api import memcache
from google.appengine.api import taskqueue
from datetime import date
from google.appengine.api import urlfetch
pubsub_client = pubsub.Client()
topic_name = 'vuukle-messages'
topic = pubsub_client.topic(topic_name)
# fuction to test the query parameters i.e just for testing
def sync_query(query):
client = bigquery.Client()
query_results = client.run_sync_query(query)
query_results.use_legacy_sql = False
query_results.use_query_cache = False
query_results.run()
# Drain the query results by requesting a page at a time.
page_token = None
bqdata = []
while True:
rows, total_rows, page_token = query_results.fetch_data(
max_results=10,
page_token=page_token)
bqdata.extend(rows)
for row in rows:
logging.debug(row)
if not page_token:
break
return bqdata
''' function to actually stream the json payload into the
biqquery table to by using the global function insert_all'''
def stream_data(dataset_name, table_name, json_data, ip, time_stamp=time.strftime("%c")):
bigquery_client = bigquery.Client()
dataset = bigquery_client.dataset(dataset_name)
table = dataset.table(table_name)
data = json_data
time_stamp1 = time.strftime("%c")
data['PAGE_VIEW_TIMESTAMP'] = time_stamp1
data['Ipaddress'] = ip
# Reload the table to get the schema.
table.reload()
# get the names of schema
temp = list()
for key in data:
temp.append(data[key])
#rows = [data]
# print rows
errors = table.insert_data([temp])
if not errors:
logging.debug('Loaded 1 row into {}:{}'.format(
dataset_name, table_name))
else:
logging.error(errors)
''' This handler is called when the given request is /bqstreamer
Uses taskqueue to call another handler as post request'''
class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.headers.add_header("Access-Control-Allow-Origin", "*")
s = self.request.url
s = urllib.unquote(s).decode('utf8')
# self.response.write(s)
start = s.index('&') + len('&')
end = s.index('&_', start)
b1 = s[start:end]
# bq=parse.unquotes(b1)
b1 = b1.replace("'", '"')
ip = self.request.remote_addr
task = taskqueue.add(
url='/bq-task', params={'bq': b1, 'ts': str(time.time()), 'Ip': ip})
def post(self):
self.response.headers.add_header("Access-Control-Allow-Origin", "*")
s = self.request.url
s = urllib.unquote(s).decode('utf8')
# self.response.write(s)
try:
start = s.index('&') + len('&')
end = s.index('&_', start)
b1 = s[start:end]
# bq=parse.unquotes(b1)
b1 = b1.replace("'", '"')
except:
return
# ts=str(time.time())
#b = json.loads(b1)
# b.replace("'",'"')
# self.response.write(b)
task = taskqueue.add(
url='/bq-task', params={'bq': b1, 'ts': str(time.time())})
'''Handler gets post reequest from the MainHandler and call stream
data to insert the data into the biqquery'''
class BqHandler(webapp2.RequestHandler):
def post(self):
# get example.com/bq-task?bq=blah
b1 = self.request.get("bq")
ts = self.request.get("ts")
ip = self.request.get("Ip")
try:
b = json.loads(b1, object_pairs_hook=OrderedDict)
logging.debug('json load: {}'.format(b))
except:
logging.debug('Cannot able to load')
return
if len(b) > 0:
datasetId = os.environ['DATASET_ID']
tableId = os.environ['TABLE_ID']
today = date.today().strftime("%Y%m%d")
tableId = "%s$%s" % (tableId, today)
stream_data(datasetId, tableId, b, ip, ts)
class PublishHandler(webapp2.RequestHandler):
urlfetch.set_default_fetch_deadline(15)
def get(self):
# flag=1
self.response.headers.add_header("Access-Control-Allow-Origin", "*")
s = self.request.url
s = urllib.unquote(s).decode('utf8')
# self.response.write(s)
start = s.index('{') + len('')
end = s.index('}', start)
b1 = s[start:end]+'}'
# bq=parse.unquotes(b1)
# b1=b1.replace("'",'"')
# b1=json.dumps(b1)
b = json.loads(b1, object_pairs_hook=OrderedDict, strict=False)
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
b['PAGE_VIEW_TIMESTAMP'] = timestamp
Ip = self.request.remote_addr
b['Ipaddress'] = Ip
a = json.dumps(b)
c = str(a)
logging.debug('json decoded')
# logging.debug(b1)
# for topic in pubsub_client.list_topics():
# if topic.name=='my-new-topic':
# flag=0
# topic.create()
# if flag==0:
# topic.create()
# print('Topic {} created.'.format(topic.name))
# b1 = b1.encode('utf-8')
# message_id = topic.publish(b1)
# logging.debug('Message {} published.'.format(message_id))
# else:
# # Data must be a bytestring
try:
c = c.encode('utf-8')
message_id = topic.publish(c)
logging.debug(
'Message {} published outside loop.'.format(message_id))
except:
c = c.encode('utf-8')
message_id = topic.publish(c)
logging.debug(
'Message {} published in except loop.'.format(message_id))
def post(self):
self.response.headers.add_header("Access-Control-Allow-Origin", "*")
pubsub_client = pubsub.Client()
# flag=1
s = self.request.url
s = urllib.unquote(s).decode('utf8')
# self.response.write(s)
start = s.index('&') + len('&')
end = s.index('&_', start)
b1 = s[start:end]
# bq=parse.unquotes(b1)
b1 = b1.replace("'", '"')
# b1=json.dumps(b1)
b = json.loads(b1, object_pairs_hook=OrderedDict, strict=False)
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
b['PAGE_VIEW_TIMESTAMP'] = timestamp
a = json.dumps(b)
c = str(a)
# for topic in pubsub_client.list_topics():
# if topic.name=='my-new-topic':
# flag=0
topic_name = 'vuukle-messages'
topic = pubsub_client.topic(topic_name)
# if flag==0:
# topic.create()
# #self.response.write('Topic {} created.'.format(topic.name))
# b1 = b1.encode('utf-8')
# message_id = topic.publish(b1)
# #self.response.write('Message {} published.'.format(message_id))
# else:
# # Data must be a bytestring
c = c.encode('utf-8')
message_id = topic.publish(c)
logging.debug('Message {} published.'.format(message_id))
app = webapp2.WSGIApplication([
('/bq-streamer', MainHandler),
('/bq-task', BqHandler),
('/bq-publish', PublishHandler),
], debug=True)