File size: 1,737 Bytes
a8c39f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f017d24
a8c39f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import os
import socket
import subprocess
import time
import requests
import json

# Constants
NOW_DIR = os.getcwd()
CONFIG_FILE = os.path.join(NOW_DIR, "assets", "config.json")
ENV_PATH = os.path.join(NOW_DIR, "env", "python.exe")
FLASK_SCRIPT_PATH = os.path.join(NOW_DIR, "assets", "flask", "routes.py")
HOST = "localhost"
PORT = 8000
TIMEOUT = 2


# Functions
def start_flask():
    """
    Starts the Flask server if it's not already running.
    """
    try:
        # Check if Flask server is already running
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            sock.settimeout(TIMEOUT)
            sock.connect((HOST, PORT))
            print("Flask server is already running. Trying to restart it.")
            requests.post("http://localhost:8000/shutdown")
            time.sleep(3)

    except socket.timeout:
        # Start the Flask server
        try:
            subprocess.Popen(
                [ENV_PATH, FLASK_SCRIPT_PATH],
                creationflags=getattr(subprocess, "CREATE_NEW_CONSOLE", 0),
            )
        except Exception as error:
            print(f"An error occurred starting the Flask server: {error}")


def load_config_flask():
    """
    Loads the Flask server configuration from the config.json file.
    """
    with open(CONFIG_FILE, "r") as file:
        config = json.load(file)
        return config["flask_server"]


def save_config(value):
    """
    Saves the Flask server configuration to the config.json file.
    """
    with open(CONFIG_FILE, "r", encoding="utf8") as file:
        config = json.load(file)
        config["flask_server"] = value
    with open(CONFIG_FILE, "w", encoding="utf8") as file:
        json.dump(config, file, indent=2)