-
Notifications
You must be signed in to change notification settings - Fork 4
/
pubsub_to_bigquery.py
138 lines (110 loc) · 3.54 KB
/
pubsub_to_bigquery.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
#!/usr/bin/env python
# ----------------------------------------------
# Google PubSub to BigQuery Demo
# Using Fake Stock Price
# ----------------------------------------------
import time
import argparse
import random
import datetime
import json
from pprint import pprint
from google.cloud import pubsub
from google.cloud import bigquery
# ----------------------------------------------
# Basic PubSub
# ----------------------------------------------
topic_name = 'stock'
subscriber_name = 'stockReceiver'
dataset_name = 'demo_stock'
table_name = 'google'
def create_topic():
pubsub_client = pubsub.Client()
topic = pubsub_client.topic(topic_name)
topic.create()
print 'Topic {} created'.format(topic_name)
def create_subscriber():
pubsub_client = pubsub.Client()
topic = pubsub_client.topic(topic_name)
subscriber = topic.subscription(subscriber_name)
subscriber.create()
print 'Subscriber {} created'.format(subscriber_name)
def publish_message(data):
pubsub_client = pubsub.Client()
topic = pubsub_client.topic(topic_name)
data = data.encode('utf-8')
message_id = topic.publish(data)
print 'Message ID:{} published to topic {}'.format(message_id,topic_name)
# ----------------------------------------------
# Fabricating Stock Price
# ----------------------------------------------
def stock_price(price):
if random.random() > .5:
price = price + random.random()
else:
price = price - random.random()
return price
def today_timestamp():
d = datetime.date.today()
ymd = d.isoformat()
return ymd
# ----------------------------------------------
# Generating 100 stock prices
# ----------------------------------------------
def deliver_stock_price(price):
counter = 1
today = today_timestamp()
hms_time = datetime.datetime.strptime('9:30:00', '%H:%M:%S')
quote = 'GOOGL'
name = 'Alphabet Inc.'
stock = price
for i in xrange(0,100): # change this to a multiple of 100 or 10
hms_time = hms_time + datetime.timedelta(0,1)
stock = stock_price(stock)
data = '{},{},{},{},{}'.format(today,hms_time.strftime('%H:%M:%S'),quote,name,stock)
publish_message(data)
counter = counter + 1
return counter
# ----------------------------------------------
# Streaming the data to BigQuery
# Batch Size = 10
# ----------------------------------------------
def stream_data_bigquery(counter):
pubsub_client = pubsub.Client()
topic = pubsub_client.topic(topic_name)
subscriber = topic.subscription(subscriber_name)
bigquery_client = bigquery.Client()
dataset = bigquery_client.dataset(dataset_name)
table = dataset.table(table_name)
batch = []
i = 0
while i < counter:
results = subscriber.pull(return_immediately=False)
if results:
for ack_id, message in results:
print '* {}: {}, {}'.format(message.message_id, message.data, message.attributes)
subscriber.acknowledge([ack_id for ack_id, message in results])
batch.append(message.data)
if len(batch) < 10: # batch size
i = i + 1
else:
for j in xrange(0,len(batch)):
dict_ = {}
data = batch[j].split(',')
table.reload()
errors = table.insert_data([data])
if not errors:
print('Loaded 1 row into {}:{}'.format(dataset_name, table_name))
else:
print('Errors:')
pprint(errors)
del batch[:]
i = i + 1
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--price', help='Give an initial Google stock price', required=True, type=float)
args = parser.parse_args()
create_topic()
create_subscriber()
counter = deliver_stock_price(args.price)
stream_data_bigquery(counter)