#!/usr/bin/env python """Part of the Weir project. This will listen on two endpoints, and when data is posted to the proper one, matching a particular format, it will save that data to a local sqlite3 db.""" __version__ = "0.1.0" from datetime import datetime import logging import os from pathlib import Path from flask import Flask, redirect, url_for, request import json import sqlite3 import pdb logging.basicConfig(level=logging.DEBUG) dbpath = "warren.db" app = Flask(__name__) 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() logging.INFO(cur.lastrowid) # always make sure to close db connection after you're done conn.close() @app.route('/') def test(): return 'the website is up you little bitch' @app.route('/weir',methods = ['POST']) def weir(): """""" try: python_dict = request.get_json() write_to_db(python_dict, "warren.db") return "OK" except: return "Error.", 400 if __name__ == '__main__': app.run(debug = True)