我正在尝试检查该软件的新版本是否可用。这就是为什么我要提出要求。该请求可能要花一些时间,并延迟窗口的打开。
我应该将此请求放入函数中并在加载窗口后调用它吗?有没有办法并行发出请求?
我正在使用Python 3。
这是示例代码:
from urllib import request
import json
from pkg_resources import parse_version
from PyQt5 import QtWidgets
from . import widgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self._menu = self.menuBar()
permanent_label = QtWidgets.QLabel()
# This request can take some time
response = request.urlopen('https://api.github.com/repos/efdiloreto/Zonda/releases/latest')
data = json.load(response)
actual_version = '0.1.0'
release_version = data['tag_name']
if parse_version(release_version) > parse_version(actual_version):
permanent_label.setText('A new version is available!')
status_bar = self.statusBar()
status_bar.setSizeGripEnabled(False)
status_bar.addWidget(permanent_label)
self._widget_central = widgets.MainWidget(self)
self.setCentralWidget(self._widget_central)
答案 0 :(得分:1)
该请求需要时间,因此有两种可能的解决方案:在线程中运行它或使用QNetworkAccessManager
异步处理这些请求,因此我的回答将使用后者。我看到您正在使用GitHub API,因此我使用文档创建了一个类,负责获取版本并将其通过信号传递。
import json
from pkg_resources import parse_version
from PyQt5 import QtCore, QtWidgets, QtNetwork
# https://developer.github.com/v3/repos/releases/#get-the-latest-release
class LastReleaseGithubHelper(QtCore.QObject):
versionChanged = QtCore.pyqtSignal(str)
def __init__(self, parent=None):
super(LastReleaseGithubHelper, self).__init__(parent)
self.fmt = "https://api.github.com/repos/{owner}/{repo}/releases/latest"
self._manager = QtNetwork.QNetworkAccessManager(self)
self._manager.finished.connect(self.onFinished)
def get_version(self, owner, repo):
url = self.fmt.format(owner=owner, repo=repo)
request = QtNetwork.QNetworkRequest(QtCore.QUrl(url))
self._manager.get(request)
@QtCore.pyqtSlot(QtNetwork.QNetworkReply)
def onFinished(self, reply):
response = reply.readAll().data().decode()
data = json.loads(response)
release_version = data['tag_name']
self.versionChanged.emit(release_version)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self._menu = self.menuBar()
self.permanent_label = QtWidgets.QLabel()
status_bar = self.statusBar()
status_bar.setSizeGripEnabled(False)
status_bar.addWidget(self.permanent_label)
version_helper = LastReleaseGithubHelper(self)
version_helper.versionChanged.connect(self.verify_version)
owner = "efdiloreto"
repo = "Zonda"
version_helper.get_version(owner, repo)
@QtCore.pyqtSlot(str)
def verify_version(self, release_version):
# only test
current_version = '0.0.9'
if parse_version(release_version) > parse_version(current_version):
self.permanent_label.setText('A new version is available!')
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())