CoolFace
Apppublic

PoweRO/RBC

sourceHugging Facemitupdated 2y agoView on Hugging Face
0likes
server.py63 linesDownload Raw Back to flask
1import os
2import socket
3import subprocess
4import time
5import requests
6import sys
7import json
8
9now_dir = os.getcwd()
10sys.path.append(now_dir)
11config_file = os.path.join(now_dir, "assets", "config.json")
12env_path = os.path.join(now_dir, "env", "python.exe")
13
14host = "localhost"
15port = 8000
16
17sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
18sock.settimeout(2)
19
20
21def start_flask():
22    try:
23        sock.connect((host, port))
24        print(
25            f"Something is listening on port {port}; Probably the Flask server is already running."
26        )
27        print("Trying to start it anyway")
28        sock.close()
29        requests.post("http://localhost:8000/shutdown")
30        time.sleep(3)
31        script_path = os.path.join(now_dir, "assets", "flask", "routes.py")
32        try:
33            subprocess.Popen(
34                [env_path, script_path], creationflags=subprocess.CREATE_NEW_CONSOLE
35            )
36        except Exception as e:
37            print(f"Failed to start the Flask server")
38            print(e)
39    except Exception as e:
40        sock.close()
41        script_path = os.path.join(now_dir, "assets", "flask", "routes.py")
42        try:
43            subprocess.Popen(
44                [env_path, script_path], creationflags=subprocess.CREATE_NEW_CONSOLE
45            )
46        except Exception as e:
47            print("Failed to start the Flask server")
48            print(e)
49
50
51def load_config_flask():
52    with open(config_file, "r") as file:
53        config = json.load(file)
54        return config["flask_server"]
55
56
57def save_config(value):
58    with open(config_file, "r", encoding="utf8") as file:
59        config = json.load(file)
60        config["flask_server"] = value
61    with open(config_file, "w", encoding="utf8") as file:
62        json.dump(config, file, indent=2)
63