appDemo/amis-flask-pywebview-demo/app.py
murmur 350f52ead5 分离服务和窗口
服务添加文件锁
2024-07-04 23:14:15 +08:00

82 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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": "恭喜,注册成功!"})
# 定义锁文件的路径
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=5000, 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)