You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

100 lines
2.4 KiB

#!/usr/bin/env python
"""Part of the Weir project."""
import logging
from datetime import datetime
import os
import pdb
import json
import sqlite3
from flask import Flask, request
logging.basicConfig(level=logging.DEBUG)
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
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."""
# directory handling will go here
# 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 sqlite3.OperationalError as error:
logging.error(error)
def write_to_db(data, dbpath):
"""given a python dict and a path for the db, writes dict to db.
calls out to create a new db if one doesn't exist."""
pdb.set_trace()
if check_if_db_exists(dbpath) is not True:
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()
@app.errorhandler(Exception)
def server_error(err):
"""catch all exception handler"""
logging.exception(err)
return "exception", 400
@app.route("/")
def test():
"""healthcheck endpoint with no logic; useful for loadbalancing checks."""
return "the website is up you little bitch"
@app.route("/weir", methods=["POST"])
def weir():
"""Primary app route."""
python_dict = request.get_json()
write_to_db(python_dict, "warren.db")
return "OK"
if __name__ == "__main__":
app.run(debug=True)