Rename to follow some example stuff i've found online.

master
josiah 3 years ago
parent b0de47d532
commit 45b5a52395

@ -1,18 +1,25 @@
#!/usr/bin/env python
"""Part of the Weir project."""
__version__ = "0.1.0"
import logging
from datetime import datetime
import os
from pathlib import Path
from flask import Flask, request
import json
import sqlite3
import pdb
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)
@ -23,8 +30,7 @@ def check_if_db_exists(dbpath):
"""checks to see if the db exists"""
if os.path.exists(dbpath):
return True
else:
return False
return False
def init_new_db(dbpath):
@ -43,29 +49,51 @@ def init_new_db(dbpath):
try:
conn = sqlite3.connect(dbpath)
cur = conn.cursor()
cur.execute('''CREATE TABLE weir (date, hostname, metadata)''')
cur.execute("""CREATE TABLE weir (date, hostname, metadata)""")
conn.commit()
logging.DEBUG(sqlite3.version)
logging.DEBUG("Creating new weir table.")
logging.debug(sqlite3.version)
logging.debug("Creating new weir table.")
conn.close()
except:
logging.error(logging.ERROR[0])
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) != True:
db = init_new_db(dbpath)
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'])]
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.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."""
try:
python_dict = request.get_json()
write_to_db(python_dict, "warren.db")
return "OK"
except Exception as error:
return f"Error: {error}.", 400
if __name__ == "__main__":
app.run(debug=True)