我有一个控制flask应用程序接口的webview。
webview将有一个启动flask server的按钮和一个停止服务器的按钮。这就是为什么我必须使用multiprocessing.Process为Flask创建一个单独的进程。这样,我就无法再访问我的pywebview.Window了。我想使用pywebview.Window在Flask进程中使用pywebview.Window.evaluate_js()评估一些javascript (当然,它必须是我在为Flask打开一个新进程之前已经创建的同一个pywebview.Window )。有谁知道如何解决这个问题。我很感激!
一些示例代码:
from flask import Flask, request, jsonify
import os, sys, re, json, socket, sqlite3, base64, requests, webview
from flask_cors import CORS
class ServerFlaskApi:
def __init__(self):
self.app = Flask(__name__, root_path=Root_Dir)
self.app.add_url_rule("/", view_func=self.Default)
def Default(self):
return "Welcome to the Python Http Server for your Application!", 200
def PrintToWebViewConsole(self):
#Trying to use pywebview.Window here, of course WebviewWindow is not defined!!!
WebviewWindow.evaluate_js(js_script)
################
class WebviewApi:
def __init__(self):
self.server_thread = None
def StartServer(self):
self.server_thread = multiprocessing.Process(target=Run_Flask_Server, daemon=True)
self.server_thread.start()
def StopServer(self):
self.server_thread.terminate()
def Run_Flask_Server():
serverApi = ServerFlaskApi()
CORS(serverApi.app)
serverApi.app.run(host=Server_Host, port=Server_Port, debug=True, use_reloader=False)
################
if __name__ == "__main__":
WebViewApi = WebviewApi()
WebviewWindow = webview.create_window(title="Server Monitor", url="view/main-gui.html", js_api=WebViewApi, width=550, height=750, min_size=(550, 750), resizable=False, on_top=True, confirm_close=False)
webview.start(debug=False)我在Python上还是个新手,所以欢迎任何建议!
提前谢谢你!
发布于 2021-09-07 13:26:04
我想我必须使用Threading而不是Processing,因为Thread共享内存,而Process不共享内存。此外,对于任何想要停止Thread的人,这里有一个函数可以做到这一点,虽然不确定这是不是一个好方法,但它可以为我做这件事:
def Kill_Thread(thread):
if not isinstance(thread, threading.Thread):
raise TypeError("Must be set as threading.Thread type!!!")
thread_id = thread.ident
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, ctypes.py_object(SystemExit))
if res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
print("Exception raise failure")https://stackoverflow.com/questions/69020223
复制相似问题