Pushing existing body of work.
This commit is contained in:
62
writer.py
Normal file
62
writer.py
Normal file
@@ -0,0 +1,62 @@
|
||||
#! env/bin/python3
|
||||
|
||||
# import the psycopg2 database adapter for PostgreSQL
|
||||
import psycopg2
|
||||
from psycopg2.extras import Json
|
||||
import json
|
||||
import sys
|
||||
|
||||
def connect_db(db: str,host: str,user: str,passwd: str):
|
||||
try:
|
||||
# declare a new PostgreSQL connection object
|
||||
conn = psycopg2.connect(
|
||||
dbname = db,
|
||||
user = user,
|
||||
host = host,
|
||||
password = passwd,
|
||||
# attempt to connect for 3 seconds then raise exception
|
||||
connect_timeout = 3
|
||||
)
|
||||
|
||||
except (Exception, psycopg2.Error) as err:
|
||||
# print ("\npsycopg2 connect error:", err)
|
||||
conn = None
|
||||
return conn
|
||||
|
||||
def get_db_creds(file: str):
|
||||
with open(file) as cred_file:
|
||||
creds = json.load(cred_file)
|
||||
return creds
|
||||
|
||||
def insert_data(conn, data):
|
||||
|
||||
# insert a new vendor into the vendors table
|
||||
sql = """
|
||||
INSERT INTO
|
||||
air(datetime, temperature, humidity, location)
|
||||
VALUES
|
||||
(%s, %s, %s, %s)
|
||||
"""
|
||||
|
||||
try:
|
||||
# open cursor on our db connection
|
||||
cur = conn.cursor()
|
||||
|
||||
# execute the INSERT statement
|
||||
data = (data["datetime"], data["temperature"], data["humidity"], data["location"])
|
||||
cur.execute(sql,data)
|
||||
|
||||
# commit the changes to the database
|
||||
conn.commit()
|
||||
|
||||
# close communication with the database
|
||||
cur.close()
|
||||
|
||||
except (Exception, psycopg2.DatabaseError) as error:
|
||||
# print(error)
|
||||
pass
|
||||
|
||||
finally:
|
||||
if conn is not None:
|
||||
conn.close()
|
||||
|
||||
Reference in New Issue
Block a user