Register API with zeroconf

This commit is contained in:
Santiago Lo Coco 2024-11-03 23:25:07 +01:00
parent 079281583f
commit ae6a84efc3
6 changed files with 49 additions and 4 deletions

View File

@ -1,5 +1,7 @@
name: GetEndpoints
services:
flask-api:
api:
build:
context: ../src
dockerfile: ../docker/Dockerfile

View File

@ -1,2 +1,6 @@
DATABASE=sqlite:///endpoints.db
API_HOST=windows.local
API_HOST=windows.local
SERVICE_NAME=RoomF7203
SERVICE_TYPE=_http._tcp.local.
SERVICE_IP=192.168.137.1
SERVICE_PORT=5000

View File

@ -3,6 +3,7 @@ from flask import Flask, render_template
from api import api
from config import API_HOST, DATABASE_URI
from db import get_endpoints_from_db, init_db
from register import register_service, unregister_service
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = DATABASE_URI
@ -19,4 +20,9 @@ def homepage():
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
register_service()
try:
app.run(host="0.0.0.0", port=5000)
finally:
unregister_service()

View File

@ -6,3 +6,7 @@ load_dotenv()
DATABASE_URI = os.getenv("DATABASE")
API_HOST = os.getenv("API_HOST")
SERVICE_NAME = os.getenv("SERVICE_NAME")
SERVICE_TYPE = os.getenv("SERVICE_TYPE")
SERVICE_IP = os.getenv("SERVICE_IP")
SERVICE_PORT = os.getenv("SERVICE_PORT")

28
src/register.py Normal file
View File

@ -0,0 +1,28 @@
from zeroconf import ServiceInfo, Zeroconf
from config import API_HOST, SERVICE_IP, SERVICE_NAME, SERVICE_PORT, SERVICE_TYPE
zeroconf = Zeroconf()
info = ServiceInfo(
type_=SERVICE_TYPE,
name=f"{SERVICE_NAME}.{SERVICE_TYPE}",
addresses=[SERVICE_IP],
port=int(SERVICE_PORT),
server=API_HOST,
properties={
"path": "/api/endpoints",
# "host": API_HOST
},
)
def register_service():
zeroconf.register_service(info)
print(f"Service {SERVICE_NAME}.{SERVICE_TYPE} registered")
def unregister_service():
zeroconf.unregister_service(info)
print(f"Service {SERVICE_NAME}.{SERVICE_TYPE} unregistered")
zeroconf.close()

View File

@ -3,4 +3,5 @@ waitress==3.0.0
python-dotenv==1.0.1
SQLAlchemy==2.0.36
Flask-SQLAlchemy==3.1.1
Gunicorn==23.0.0
Gunicorn==23.0.0
Zeroconf==0.136.0