gpt4 book ai didi

python - 异步Python函数处理PHP

转载 作者:行者123 更新时间:2023-12-01 00:19:54 25 4
gpt4 key购买 nike

我正在使用 pyqt5 开发一个应用程序,该应用程序通过 QtWebChannel 作为 Web 应用程序工作,当您单击 html 中带有“Python”文本的按钮时,将执行一个 js 函数(login_py)来恢复输入的值( #request )并显示一个 gif (loader.gif),指示正在处理请求,然后通过后端将该值发送到 python,并通过 python 执行 php_function 函数,该函数处理来自 php 文件 (login.php) 的调用,一旦结束,删除 gif 并将 php 响应放置在一个跨度中 (#response)。

我的问题是,当按下“Python”按钮时,应用程序窗口会暂时卡住,发生这种情况并不令人愉快,此外,表明正在加载的gif从未出现,我想知道是否该请求可以以更类似于 ajax 请求的方式发出,其中窗口不会卡住。

或者,有一个带有文本“Javascript”的按钮,可以通过ajax处理请求,这就像我希望的“Python”按钮的请求一样。

我澄清,原始的login.php文件往往需要未知的时间来响应,为了不放置整个原始代码,我留下这个模拟我的情况的修改后的login.php。

login.php

<?php
error_reporting(0);
sleep(5);
header("Content-type: application/json");
if ($argv[1]) {
$var = $argv[1];
} else {
$var = $_GET['one'];
}
echo '{"one":"'.$var.'"}';
?>

测试.py

from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets, QtWebChannel
import json
import os

#path = "http://localhost/test.html"
path = "test.html"
dirr = os.path.join(os.path.dirname(os.path.realpath(__file__)), path)

class Backend(QtCore.QObject):
valueChanged = QtCore.pyqtSignal(str)
def __init__(self, parent=None):
super().__init__(parent)
self._value = ""

@QtCore.pyqtProperty(str)
def value(self):
return self._value

@value.setter
def value(self, v):
self._value = v
self.valueChanged.emit(v)

class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.webEngineView = QtWebEngineWidgets.QWebEngineView()
lay = QtWidgets.QVBoxLayout(self)
lay.setContentsMargins(0, 0, 0, 0)
lay.addWidget(self.webEngineView)
backend = Backend(self)
backend.valueChanged.connect(self.php_function)
self.channel = QtWebChannel.QWebChannel()
self.channel.registerObject("backend", backend)
self.webEngineView.page().setWebChannel(self.channel)
#self.webEngineView.setUrl(QtCore.QUrl(path))
self.webEngineView.setUrl(QtCore.QUrl.fromLocalFile(dirr))

@QtCore.pyqtSlot(str)
def php_function(self, value):
data = os.popen('php login.php ' + value).read()
data = json.loads(data)
self.webEngineView.page().runJavaScript('$("#loader").removeAttr("src"); $("#response").text("'+data["one"]+'");')

if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())

test.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
</head>
<script type="text/javascript">
var backend = null;
if (typeof QWebChannel !== "undefined") {
new QWebChannel(qt.webChannelTransport, function (channel) {
backend = channel.objects.backend;
});
}
function login_py(request) {
$("#loader").attr("src", "loader.gif");
backend.value = request;
}
function login_js(request) {
$("#loader").attr("src", "loader.gif");
$.ajax({
url: 'login.php',
type: 'get',
data: {one:request},
success: function (data) {
$("#loader").removeAttr("src");
$("#response").text(data.one);
}
})
}
</script>
<body>
<input id="request">
<button onclick="login_js($('#request').val())">Javascript</button>
<button onclick="login_py($('#request').val())">Python</button>
<br>
<br>
<img id="loader">
<span id="response"></span>
</body>
</html>

最佳答案

os.popen() 是一个阻塞任务,它会卡住 Qt 的事件循环,导致 GUI 卡住,因此您必须将该方法替换为不阻塞的方法,例如使用 QProcess 或者在极端情况下在另一个线程上运行它,在这种情况下使用 QProcess 并异步发送信息就足够了。

import json
import os

from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets, QtWebChannel


current_dir = os.path.dirname(os.path.realpath(__file__))
# path = "http://localhost/test.html"
path = "test.html"
dirr = os.path.join(current_dir, path)


class Backend(QtCore.QObject):
valueChanged = QtCore.pyqtSignal(str)

def __init__(self, parent=None):
super().__init__(parent)
self._value = ""

@QtCore.pyqtProperty(str, notify=valueChanged)
def value(self):
return self._value

@value.setter
def value(self, v):
self._value = v
self.valueChanged.emit(v)


class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.webEngineView = QtWebEngineWidgets.QWebEngineView()
lay = QtWidgets.QVBoxLayout(self)
lay.setContentsMargins(0, 0, 0, 0)
lay.addWidget(self.webEngineView)
backend = Backend(self)
backend.valueChanged.connect(self.php_function)
self.channel = QtWebChannel.QWebChannel()
self.channel.registerObject("backend", backend)
self.webEngineView.page().setWebChannel(self.channel)
# self.webEngineView.setUrl(QtCore.QUrl(path))
self.webEngineView.setUrl(QtCore.QUrl.fromLocalFile(dirr))

self._php_process = PhpProcess()
self._php_process.resultChanged.connect(self.process_php_result)

@QtCore.pyqtSlot(str)
def php_function(self, value):
self._php_process.execute(value)

@QtCore.pyqtSlot(str)
def process_php_result(self, data):
data = json.loads(data)
self.webEngineView.page().runJavaScript(
'$("#loader").removeAttr("src"); $("#response").text("'
+ data["one"]
+ '");'
)


class PhpProcess(QtCore.QObject):
resultChanged = QtCore.pyqtSignal(str)

def __init__(self, parent=None):
super().__init__(parent)
self._process = QtCore.QProcess(self)
self._process.readyReadStandardOutput.connect(self.on_readyReadStandardOutput)

@QtCore.pyqtSlot(str)
def execute(self, parameter):
self._process.start("php", [os.path.join(current_dir, "login.php"), parameter])

@QtCore.pyqtSlot()
def on_readyReadStandardOutput(self):
output = self._process.readAllStandardOutput()
self.resultChanged.emit(output.data().decode())


if __name__ == "__main__":
import sys

app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())

关于python - 异步Python函数处理PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59022127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com