python-3.xflaskwebviewmultiprocessingpywebview

How to Access pywebview.Window Object from Another multiprocessing.Process?


I have a webview that controlling the flask api.

The webview will have a button to start the flask server and a button to stop the server. That is why I have to use multiprocessing.Process to create a separate process for Flask. With that, I cannot access my pywebview.Window anymore. I want to use pywebview.Window to evaluate some javascript with pywebview.Window.evaluate_js() within the Flask process (of course it has to be the same pywebview.Window that I already created before open a new process for Flask). Is anybody know how to accomplish this issue. I appreciate it!

Some sample code:

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)

I'm still new in Python, so any suggestion is welcome!

Thank you in advance!


Solution

  • I guess I have to use Threading instead of Processing, since Thread is sharing memory and Process is not. Also, for anybody who want to stop a Thread, here is a function to do that, not sure if this is a good way to do it, but it does the job for me:

    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")