#!/usr/bin/env python """Part of the Weir project.""" import logging from datetime import datetime import os from pathlib import Path import json import sqlite3 import pdb def parse_incoming_post(body): """given a body of a request, convert it from json to pydict""" json_dict = json.loads(body) return json_dict def check_if_db_exists(dbpath): """checks to see if the db exists""" if os.path.exists(dbpath): return True else: return False def init_new_db(dbpath): """when you create a DB connection with SQLite3 you will automatically create a db file if one is not there. This function handles explicitly creating the folder structure and inniting the connection as required. You can specify your own dbpath, or you can use the default dbpath.""" # TODO: write directory handling shit # handle the DB stuff conn = None try: conn = sqlite3.connect(dbpath) cur = conn.cursor() cur.execute('''CREATE TABLE weir (date, hostname, metadata)''') conn.commit() logging.DEBUG(sqlite3.version) logging.DEBUG("Creating new weir table.") conn.close() except: logging.error(logging.ERROR[0]) def write_to_db(data, dbpath): pdb.set_trace() if check_if_db_exists(dbpath) != True: db = init_new_db(dbpath) conn = sqlite3.connect(dbpath) cur = conn.cursor() right_now = datetime.utcnow().strftime("%Y%m%d") sql_inputs = [(right_now, data['hostname'], data['metadata'])] cur.executemany("INSERT INTO weir VALUES (?,?,?)", sql_inputs) conn.commit() # always make sure to close db connection after you're done conn.close()