-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreceive_barcode.py
More file actions
executable file
·51 lines (41 loc) · 1.58 KB
/
receive_barcode.py
File metadata and controls
executable file
·51 lines (41 loc) · 1.58 KB
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
#!/usr/bin/env python3
import pika, sys, os, json, pymongo
from buycott_scraper import BuycottScraper
def main():
credentials = pika.PlainCredentials(os.environ['RABBITMQ_USER'], os.environ['RABBITMQ_USER_PW'])
connection = pika.BlockingConnection(pika.ConnectionParameters(
host=os.environ['RABBITMQ_DEV_HOST'],
credentials=credentials))
channel = connection.channel()
channel.queue_declare(queue='buycott', durable=True)
def connect_db():
client = pymongo.MongoClient(
os.environ['MONGODB_DEV_URI'])
db = client.dev
return db
def save_product(db, product):
db["products"].insert_one(product)
print(" [+] Product successfully saved.")
def callback(ch, method, properties, code):
print(f" [!] Received {code} \n Starting Scraper... ")
scraper = BuycottScraper(code)
product = scraper.scrape()
print("Scraped New Product:\n", json.dumps(product, indent=4, sort_keys=True))
try:
db = connect_db()
save_product(db, product)
except Exception as e:
print(f"Error while saving product {str(e)}")
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.basic_consume(queue='buycott', on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('Interrupted')
try:
sys.exit(0)
except SystemExit:
os._exit(0)