Skip to content

Commit

Permalink
Fixes for gunicorn
Browse files Browse the repository at this point in the history
  • Loading branch information
bertybuttface committed Apr 10, 2024
1 parent 0252e9e commit 1a81c4e
Show file tree
Hide file tree
Showing 7 changed files with 63 additions and 51 deletions.
12 changes: 6 additions & 6 deletions queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,9 @@ def get_records_for_date_hour(date, hour):
record["display_name"]
) # Access the field by name
record_dict = dict(record) # Convert the record to a dictionary
record_dict[
"common_name"
] = common_name # Add the 'common_name' key to the record dictionary
record_dict["common_name"] = (
common_name # Add the 'common_name' key to the record dictionary
)
result.append(record_dict)

conn.close()
Expand Down Expand Up @@ -158,9 +158,9 @@ def get_records_for_scientific_name_and_date(scientific_name, date):
record["display_name"]
) # Access the field by name
record_dict = dict(record) # Convert the record to a dictionary
record_dict[
"common_name"
] = common_name # Add the 'common_name' key to the record dictionary
record_dict["common_name"] = (
common_name # Add the 'common_name' key to the record dictionary
)
result.append(record_dict)

conn.close()
Expand Down
42 changes: 3 additions & 39 deletions speciesid.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import json
import multiprocessing
import sqlite3
import sys
import time
Expand All @@ -13,8 +12,7 @@
from tflite_support.task import core, processor, vision

from queries import get_common_name
from util import load_config
from webui import app
from util import load_config, setupdb

classifier = None
config = load_config()
Expand Down Expand Up @@ -234,33 +232,6 @@ def on_message(client, userdata, message):
conn.close()


def setupdb():
conn = sqlite3.connect(DBPATH)
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS detections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
detection_time TIMESTAMP NOT NULL,
detection_index INTEGER NOT NULL,
score REAL NOT NULL,
display_name TEXT NOT NULL,
category_name TEXT NOT NULL,
frigate_event TEXT NOT NULL UNIQUE,
camera_name TEXT NOT NULL
)
"""
)
conn.commit()

conn.close()


def run_webui():
print("Starting flask app", flush=True)
app.run(debug=False, host=config["webui"]["host"], port=config["webui"]["port"])


def run_mqtt_client():
print(
"Starting MQTT client. Connecting to: " + config["frigate"]["mqtt_server"],
Expand Down Expand Up @@ -311,15 +282,8 @@ def main():

# setup database
setupdb()
print("Starting threads for Flask and MQTT", flush=True)
flask_process = multiprocessing.Process(target=run_webui)
mqtt_process = multiprocessing.Process(target=run_mqtt_client)

flask_process.start()
mqtt_process.start()

flask_process.join()
mqtt_process.join()
print("Starting MQTT (flask disabled, use gunicorn)", flush=True)
run_mqtt_client()


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="/">Who's At My Feeder?</a>
<a class="navbar-brand" href="{{ url_for('index') }}">Who's At My Feeder?</a>
{% if title_text %}
<span class="navbar-text">
{% if title_link %}
Expand Down
5 changes: 3 additions & 2 deletions templates/daily_summary.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

{% block date_picker %}
<form class="d-flex">
<input type="date" id="date-picker" class="form-control" value="{{ date }}" min="{{ earliest_date }}" max="{{ today }}" onchange="navigateToDailySummary(this)" />
<input type="date" id="date-picker" class="form-control" value="{{ date }}" min="{{ earliest_date }}" max="{{ date }}" data-daily-summary-url="{{ url_for('show_daily_summary_dummy') }}" onchange="navigateToDailySummary(this)" />
</form>
{% endblock %}

Expand Down Expand Up @@ -54,7 +54,8 @@ <h2>Daily Summary for {{ date }}</h2>
<script>
function navigateToDailySummary(input) {
const selectedDate = input.value;
window.location.href = `/daily_summary/${selectedDate}`;
const baseUrl = input.getAttribute('data-daily-summary-url');
window.location.href = baseUrl + selectedDate;
}
</script>
{% endblock %}
5 changes: 3 additions & 2 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

{% block date_picker %}
<form class="d-flex">
<input type="date" id="date-picker" class="form-control" value="{{ date }}" min="{{ earliest_date }}" max="{{ date }}" onchange="navigateToDailySummary(this)" />
<input type="date" id="date-picker" class="form-control" value="{{ date }}" min="{{ earliest_date }}" max="{{ date }}" data-daily-summary-url="{{ url_for('show_daily_summary_dummy') }}" onchange="navigateToDailySummary(this)" />
</form>
{% endblock %}

Expand Down Expand Up @@ -83,7 +83,8 @@ <h2>Detection Summary</h2>
<script>
function navigateToDailySummary(input) {
const selectedDate = input.value;
window.location.href = `/daily_summary/${selectedDate}`;
const baseUrl = input.getAttribute('data-daily-summary-url');
window.location.href = baseUrl + selectedDate;
}
</script>
{% endblock %}
23 changes: 23 additions & 0 deletions util.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
import sqlite3

import yaml

Expand All @@ -8,3 +9,25 @@ def load_config():
with open(file_path, "r") as config_file:
config = yaml.safe_load(config_file)
return config


def setupdb():
config = load_config()
conn = sqlite3.connect(config["database"]["path"])
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS detections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
detection_time TIMESTAMP NOT NULL,
detection_index INTEGER NOT NULL,
score REAL NOT NULL,
display_name TEXT NOT NULL,
category_name TEXT NOT NULL,
frigate_event TEXT NOT NULL UNIQUE,
camera_name TEXT NOT NULL
)
"""
)
conn.commit()
conn.close()
25 changes: 24 additions & 1 deletion webui.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,27 @@
get_earliest_detection_date, get_records_for_date_hour,
get_records_for_scientific_name_and_date,
recent_detections)
from util import load_config
from util import load_config, setupdb


class ReverseProxied(object):
def __init__(self, app):
self.app = app

def __call__(self, environ, start_response):
script_name = environ.get("HTTP_X_INGRESS_PATH", "")
if script_name:
environ["SCRIPT_NAME"] = script_name
else:
print(f"HTTP_X_INGRESS_PATH: {script_name}", flush=True)
return self.app(environ, start_response)


app = Flask(__name__)
app.wsgi_app = ReverseProxied(app.wsgi_app)

config = load_config()
setupdb()
DBPATH = config["database"]["path"]
NAMEDBPATH = config["classification"]["name_database"]

Expand Down Expand Up @@ -130,6 +147,12 @@ def show_detections_by_scientific_name(scientific_name, date, end_date):
)


@app.route("/daily_summary/")
def show_daily_summary_dummy(date):
# Return a 404, the user shouldn't be here.
abort(404)


@app.route("/daily_summary/<date>")
def show_daily_summary(date):
date_datetime = datetime.strptime(date, "%Y-%m-%d")
Expand Down

0 comments on commit 1a81c4e

Please sign in to comment.