103 lines
2.5 KiB
Python
103 lines
2.5 KiB
Python
from flask import Flask, jsonify, render_template,request
|
||
import json
|
||
|
||
import os
|
||
import sys
|
||
import filelock
|
||
|
||
def resource_path(relative_path):
|
||
""" Get absolute path to resource, works for dev and for PyInstaller """
|
||
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
|
||
return os.path.join(base_path, relative_path)
|
||
|
||
app = Flask(__name__, static_folder=resource_path('web'), static_url_path='')
|
||
|
||
@app.route('/')
|
||
def index():
|
||
return app.send_static_file('index.html')
|
||
|
||
@app.route('/api/config')
|
||
def get_config():
|
||
with open('cfg.json', 'r', encoding='utf-8') as f:
|
||
config = json.load(f)
|
||
return jsonify(config)
|
||
|
||
|
||
@app.route('/saveForm', methods=['POST'])
|
||
def submit():
|
||
username = request.json.get('name')
|
||
password = request.json.get('email')
|
||
|
||
# 执行提交逻辑
|
||
print(username,password)
|
||
|
||
return jsonify({"code": 0, "msg": "恭喜,注册成功!"})
|
||
|
||
|
||
@app.route('/api/getStatus')
|
||
def getStatus():
|
||
#产生三组随机数,随机数在-1 0 1之间
|
||
import random
|
||
import time
|
||
time.sleep(1)
|
||
a = random.randint(-1, 1)
|
||
b = random.randint(-1, 1)
|
||
c = random.randint(-1, 1)
|
||
return jsonify({"code": 0, "data": {'state':[a, b, c]}})
|
||
|
||
|
||
@app.route('/sendData',methods=['POST'])
|
||
def sendUPD():
|
||
#print the keys and values of the request
|
||
print(request.json)
|
||
return jsonify({"code": 0, "msg": "发送指令成功!"})
|
||
|
||
|
||
|
||
# 定义锁文件的路径
|
||
LOCKFILE = 'app.lock'
|
||
|
||
def acquire_lock(lock_file):
|
||
"""
|
||
获取文件锁
|
||
|
||
Args:
|
||
lock_file: 锁文件路径
|
||
|
||
Returns:
|
||
FileLock 对象 如果成功获取锁,None 否则
|
||
"""
|
||
try:
|
||
lock = filelock.FileLock(lock_file)
|
||
lock.acquire(timeout=1)
|
||
return lock
|
||
except filelock.Timeout:
|
||
return None
|
||
|
||
def release_lock(lock):
|
||
if lock:
|
||
lock.release()
|
||
|
||
def start_flask():
|
||
app.run(debug=True, port=80, use_reloader=False)
|
||
|
||
if __name__ == '__main__':
|
||
# 以进程方式运行服务
|
||
# import threading
|
||
# flask_thread = threading.Thread(target=start_flask)
|
||
# flask_thread.daemon = True
|
||
# flask_thread.start()
|
||
|
||
|
||
lock = acquire_lock(LOCKFILE)
|
||
if not lock:
|
||
print("Another instance is already running. Exiting...")
|
||
sys.exit(1)
|
||
|
||
# 启动 Flask 服务器
|
||
print("Starting Flask server...")
|
||
start_flask()
|
||
|
||
# 服务器启动后,下面的代码将不会被立即执行,直到服务器停止
|
||
print("This line will not be executed until the server stops.")
|
||
release_lock(lock) |