mirror of
https://github.com/Casvt/MIND.git
synced 2026-04-03 03:00:22 -04:00
Backend Refactor
This commit is contained in:
78
MIND.py
78
MIND.py
@@ -1,20 +1,24 @@
|
||||
#!/usr/bin/env python3
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
The main file where MIND is started from
|
||||
"""
|
||||
|
||||
import logging
|
||||
from os import makedirs, urandom
|
||||
from os.path import abspath, dirname, isfile, join
|
||||
from os.path import dirname, isfile
|
||||
from shutil import move
|
||||
from sys import version_info
|
||||
|
||||
from flask import Flask, render_template, request
|
||||
from waitress.server import create_server
|
||||
from werkzeug.middleware.dispatcher import DispatcherMiddleware
|
||||
|
||||
from backend.db import DBConnection, ThreadedTaskDispatcher, close_db, setup_db
|
||||
from frontend.api import (admin_api, admin_api_prefix, api, api_prefix,
|
||||
reminder_handler)
|
||||
from frontend.ui import ui
|
||||
from backend.helpers import check_python_version, folder_path
|
||||
from backend.reminders import ReminderHandler
|
||||
from frontend.api import admin_api, admin_api_prefix, api, api_prefix
|
||||
from frontend.ui import UIVariables, ui
|
||||
|
||||
HOST = '0.0.0.0'
|
||||
PORT = '8080'
|
||||
@@ -23,35 +27,33 @@ LOGGING_LEVEL = logging.INFO
|
||||
THREADS = 10
|
||||
DB_FILENAME = 'db', 'MIND.db'
|
||||
|
||||
UIVariables.url_prefix = URL_PREFIX
|
||||
logging.basicConfig(
|
||||
level=LOGGING_LEVEL,
|
||||
format='[%(asctime)s][%(threadName)s][%(levelname)s] %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
|
||||
def _folder_path(*folders) -> str:
|
||||
"""Turn filepaths relative to the project folder into absolute paths
|
||||
Returns:
|
||||
str: The absolute filepath
|
||||
"""
|
||||
return join(dirname(abspath(__file__)), *folders)
|
||||
|
||||
def _create_app() -> Flask:
|
||||
"""Create a Flask app instance
|
||||
|
||||
Returns:
|
||||
Flask: The created app instance
|
||||
"""
|
||||
app = Flask(
|
||||
__name__,
|
||||
template_folder=_folder_path('frontend','templates'),
|
||||
static_folder=_folder_path('frontend','static'),
|
||||
template_folder=folder_path('frontend','templates'),
|
||||
static_folder=folder_path('frontend','static'),
|
||||
static_url_path='/static'
|
||||
)
|
||||
app.config['SECRET_KEY'] = urandom(32)
|
||||
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
|
||||
app.config['JSON_SORT_KEYS'] = False
|
||||
app.config['APPLICATION_ROOT'] = URL_PREFIX
|
||||
app.wsgi_app = DispatcherMiddleware(Flask(__name__), {URL_PREFIX: app.wsgi_app})
|
||||
app.wsgi_app = DispatcherMiddleware(
|
||||
Flask(__name__),
|
||||
{URL_PREFIX: app.wsgi_app}
|
||||
)
|
||||
|
||||
# Add error handlers
|
||||
@app.errorhandler(400)
|
||||
@@ -68,7 +70,7 @@ def _create_app() -> Flask:
|
||||
|
||||
@app.errorhandler(404)
|
||||
def not_found(e):
|
||||
if request.path.startswith('/api'):
|
||||
if request.path.startswith(api_prefix):
|
||||
return {'error': 'Not Found', 'result': {}}, 404
|
||||
return render_template('page_not_found.html', url_prefix=logging.URL_PREFIX)
|
||||
|
||||
@@ -83,40 +85,42 @@ def _create_app() -> Flask:
|
||||
|
||||
def MIND() -> None:
|
||||
"""The main function of MIND
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
# Check python version
|
||||
if (version_info.major < 3) or (version_info.major == 3 and version_info.minor < 7):
|
||||
logging.error('Error: the minimum python version required is python3.7 (currently ' + version_info.major + '.' + version_info.minor + '.' + version_info.micro + ')')
|
||||
logging.info('Starting up MIND')
|
||||
|
||||
if not check_python_version():
|
||||
exit(1)
|
||||
|
||||
if isfile(folder_path('db', 'Noted.db')):
|
||||
move(folder_path('db', 'Noted.db'), folder_path(*DB_FILENAME))
|
||||
|
||||
db_location = folder_path(*DB_FILENAME)
|
||||
logging.debug(f'Database location: {db_location}')
|
||||
makedirs(dirname(db_location), exist_ok=True)
|
||||
|
||||
DBConnection.file = db_location
|
||||
|
||||
# Register web server
|
||||
# We need to get the value to ui.py but MIND.py imports from ui.py so we get an import loop.
|
||||
# To go around this, we abuse the fact that the logging module is a singleton.
|
||||
# We add an attribute to the logging module and in ui.py get the value this way.
|
||||
logging.URL_PREFIX = URL_PREFIX
|
||||
app = _create_app()
|
||||
reminder_handler = ReminderHandler(app.app_context)
|
||||
with app.app_context():
|
||||
if isfile(_folder_path('db', 'Noted.db')):
|
||||
move(_folder_path('db', 'Noted.db'), _folder_path(*DB_FILENAME))
|
||||
|
||||
db_location = _folder_path(*DB_FILENAME)
|
||||
logging.debug(f'Database location: {db_location}')
|
||||
makedirs(dirname(db_location), exist_ok=True)
|
||||
|
||||
DBConnection.file = db_location
|
||||
setup_db()
|
||||
reminder_handler.find_next_reminder()
|
||||
|
||||
# Create waitress server and run
|
||||
dispatcher = ThreadedTaskDispatcher()
|
||||
dispatcher.set_thread_count(THREADS)
|
||||
server = create_server(app, _dispatcher=dispatcher, host=HOST, port=PORT, threads=THREADS)
|
||||
server = create_server(
|
||||
app,
|
||||
_dispatcher=dispatcher,
|
||||
host=HOST,
|
||||
port=PORT,
|
||||
threads=THREADS
|
||||
)
|
||||
logging.info(f'MIND running on http://{HOST}:{PORT}{URL_PREFIX}')
|
||||
# =================
|
||||
server.run()
|
||||
|
||||
# Stopping thread
|
||||
# =================
|
||||
|
||||
reminder_handler.stop_handling()
|
||||
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user