0

How can I correctly configure a Flask web server to run inside a Docker container in Homeassistant using gunicorn and nginx as reverse proxy, to show and edit content from a SQLite database?

I am currently developing a Homeassistant addon that requires a Flask web server to display and edit content from a SQLite database. The Flask web server works correctly when run on a local machine, but I am having trouble configuring it to run inside a Docker container in Homeassistant, using gunicorn as the web server and nginx as the reverse proxy.

Here is a snippet of my Flask code:

import sqlite3
from threading import Thread
from datetime import datetime
from flask import Flask, render_template, request
from Bobdatabase import BobDatabase

Server = Flask('Bobserver')

@Server.route('/')
def index():
    print("TestHome", flush=True)
    return render_template('index.html')

@Server.route('/results', methods=['POST'])
def results():
    print("TestResult", flush=True)
    conn = sqlite3.connect('bob.db')
    print(conn, flush=True)
    cursor = conn.execute('SELECT * FROM PURCHASES')
    rows = cursor.fetchall()
    columns = [column[0] for column in cursor.description]
    return render_template('results.html', columns=columns, rows=[dict(zip(columns, row)) for row in rows])

And here is a snippet of my Dockerfile:

# Install required packages
RUN apk add --no-cache python3 py3-pip 
RUN pip3 install --no-cache-dir paho-mqtt
RUN pip3 install --no-cache-dir pytz
RUN pip3 install --no-cache-dir flask
RUN pip3 install --no-cache-dir gunicorn

# Add nginx test and create the run folder for nginx
RUN \
  apk --no-cache add \
    nginx \
  \
  && mkdir -p /run/nginx

COPY Bobsite.py /
ADD templates /templates
COPY ingress.conf /etc/nginx/http.d/Bobserver.conf

COPY run.sh /
RUN chmod a+x /run.sh
CMD [ "/run.sh" ]

And here is my ingress.conf file:

upstream Bobserver {
  server 127.0.0.1:8000;
}

server {
    listen 8099;
    allow <HomeassistantIP>;
    deny all; 
    server_name Bobserver;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header POST $request_body;
    }    
}

When I install the addon inside Homeassistant and try to access the website, I am able to get to the root page of the Flask web server, but when I click the button to go to the /results page, I get a 404 error. I suspect that the reverse proxy is failing to call Flask correctly. Can anyone help me figure out what I'm doing wrong? Thank you.

0 Answers0