-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
169 lines (138 loc) · 4.91 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
from flask import Flask, request, jsonify
from kafka import KafkaProducer, KafkaConsumer
from kafka.admin import KafkaAdminClient, NewTopic
import psycopg2
import json
app = Flask(__name__)
KAFKA_BOOTSTRAP_SERVERS='kafka'
KAFKA_TOPIC='product_orders'
# function to establish postgres connection
def create_connection():
conn = psycopg2.connect(
host='db',
database='orders',
user="pritishsamal",
password="Cymatics@7",
)
return conn
# Dummy function to send email
def send_email(order):
print(f"Email sent successfully to {order['customer']['email']}...")
# Adding success callback
def on_producer_send_success(record_metadata):
print('Message sent successfully!')
# Adding failure callback
def on_producer_send_error(excp):
print('Failed to send message:', excp)
def publish_to_kafka_topic(topic, message):
producer = KafkaProducer(
bootstrap_servers=KAFKA_BOOTSTRAP_SERVERS,
value_serializer=lambda v: json.dumps(v).encode('utf-8'),
acks="all",
retries=0,
request_timeout_ms=2000,
batch_size=16384,
linger_ms=100
)
future = producer.send(topic, value=message)
producer.flush()
future.add_callback(on_producer_send_success)
future.add_errback(on_producer_send_error)
producer.close()
def consume_from_kafka_topic(topic):
consumer = KafkaConsumer(topic, bootstrap_servers=KAFKA_BOOTSTRAP_SERVERS, group_id='kafka-streamer')
return consumer
def save_order_to_postgres(order):
conn = create_connection()
cursor = conn.cursor()
query = """
INSERT INTO orders (order_id, name, email, street, city, state, postal_code, product_name, quantity, order_date, priority)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
"""
values = (
order.get('order_id'),
order.get('customer').get('name'),
order.get('customer').get('email'),
order.get('customer').get('address').get('street'),
order.get('customer').get('address').get('city'),
order.get('customer').get('address').get('state'),
order.get('customer').get('address').get('postal_code'),
order.get('product_name'),
order.get('quantity'),
order.get('order_date'),
order.get('priority')
)
cursor.execute(query, values)
conn.commit()
cursor.close()
conn.close()
def consume_and_send_emails():
consumer = consume_from_kafka_topic(KAFKA_TOPIC)
for message in consumer:
# print("Message", message.value)
order = eval(message.value.decode('utf-8'))
# print("Order", order.get('order_id'))
# Check if priority is high
if order.get('priority') == 'high':
send_email(order)
# Save order to PostgreSQL
save_order_to_postgres(order)
# Write message to respective city topic
city_topic = order.get('customer').get('address').get('city')
publish_to_kafka_topic(city_topic, order)
# Dummy Home Endpoint
@app.route("/")
def hello():
return "Hey there, welcome to the Kafka streamer!"
# CREATE and READ Orders Endpoint
@app.route("/orders", methods=["POST", "GET"])
def orders():
if request.method == "GET":
conn = create_connection()
cursor = conn.cursor()
query = "SELECT * FROM orders;"
cursor.execute(query)
rows = cursor.fetchall()
orders = []
for row in rows:
order = {
'order_id': row[0],
'name': row[1],
'email': row[2],
'street': row[3],
'city': row[4],
'state': row[5],
'postal_code': row[6],
'product_name': row[7],
'quantity': row[8],
'order_date': row[9].strftime('%Y-%m-%d'),
'priority': row[10]
}
orders.append(order)
cursor.close()
conn.close()
return jsonify(orders), 200
if request.method == "POST":
order = request.get_json()
producer = KafkaProducer(
bootstrap_servers=KAFKA_BOOTSTRAP_SERVERS,
value_serializer=lambda v: json.dumps(v).encode('utf-8'),
acks="all",
retries=0,
request_timeout_ms=2000,
batch_size=16384,
linger_ms=100
)
future = producer.send(KAFKA_TOPIC, value=order)
producer.flush()
future.add_callback(on_producer_send_success)
future.add_errback(on_producer_send_error)
producer.close()
return jsonify({'message': 'Order created successfully'}), 200
if __name__ == '__main__':
# Start consuming and sending emails in the background
import threading
email_thread = threading.Thread(target=consume_and_send_emails)
email_thread.start()
# Start the Flask web service
app.run(debug=True)