diff --git a/amis-flask-pywebview-demo/app.py b/amis-flask-pywebview-demo/app.py index fdf04dc..0abae64 100644 --- a/amis-flask-pywebview-demo/app.py +++ b/amis-flask-pywebview-demo/app.py @@ -1,9 +1,9 @@ from flask import Flask, jsonify, render_template,request import json -import webview import os import sys +import filelock def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ @@ -33,14 +33,50 @@ def submit(): 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() + # 以进程方式运行服务 + # 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) - webview.create_window("demo","http://127.0.0.1:5000") - webview.start(debug=True) + # 启动 Flask 服务器 + print("Starting Flask server...") + start_flask() + + # 服务器启动后,下面的代码将不会被立即执行,直到服务器停止 + print("This line will not be executed until the server stops.") + release_lock(lock) \ No newline at end of file diff --git a/amis-flask-pywebview-demo/window.py b/amis-flask-pywebview-demo/window.py new file mode 100644 index 0000000..754fe7f --- /dev/null +++ b/amis-flask-pywebview-demo/window.py @@ -0,0 +1,62 @@ +import webview +import socket +import sys + +ERROR_PAGE_CONTENT = """ + + + + + + Error + + + +
+

Service Not Available

+

No service is running on port 5000. Please start the Flask server first.

+
+ + +""" + +def is_port_in_use(port): + """ + 检查指定端口是否被占用。 + + 参数: + port (int): 要检查的端口号。 + + 返回: + bool: 如果端口被占用,则返回 True;否则返回 False。 + """ + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + return s.connect_ex(('127.0.0.1', port)) == 0 + +if __name__ == '__main__': + port = 5000 + if is_port_in_use(port): + webview.create_window("Demo", f"http://127.0.0.1:{port}",fullscreen=False) + else: + webview.create_window("Error", html=ERROR_PAGE_CONTENT,fullscreen=False) + + webview.start()