simple-ecowatt/simple_ecowatt/__init__.py

70 lines
1.6 KiB
Python
Raw Normal View History

2023-01-05 16:11:37 +01:00
from flask import Flask
import flask.logging
import os
import logging
import functools
from . import api
logger = logging.getLogger(__name__)
def err_handle(f):
@functools.wraps(f)
def wrap(*args, **kwargs):
try:
return f(*args, **kwargs)
except api.EmptyCache:
return ("No data available yet", 500)
except api.MissingData:
return ("No data for the current time", 500)
return wrap
def setup_logging(app: Flask):
GUNICORN_LOGGER_NAME = "gunicorn.error"
logger.addHandler(flask.logging.default_handler)
is_gunicorn = GUNICORN_LOGGER_NAME in logging.Logger.manager.loggerDict.keys()
if is_gunicorn:
gunicorn_logger = logging.getLogger(GUNICORN_LOGGER_NAME)
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)
def create_app(test_config=None):
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY="dev",
)
setup_logging(app)
if test_config is None:
logger.info("Loading config from 'config.py'")
app.config.from_pyfile("config.py")
else:
app.config.from_pyfile(test_config)
os.makedirs(app.instance_path, exist_ok=True)
state = api.ApiState(app)
@app.route("/full")
@err_handle
def full():
return state.get_json()
@app.route("/now")
@err_handle
def now():
return str(state.get_now())
@app.route("/today")
@err_handle
def today():
return str(state.get_today())
return app