我尝试用QtNetwork
写一个类来下载一个文件而不冻结我的GUI。这似乎可以用http URL(用“http://webcode.me“测试),但不能用我的例子中的https
URL。
import os
from typing import Optional
import urllib.parse
from PyQt5.QtCore import pyqtSignal, QByteArray, QFile, QObject, QUrl
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest
class AsyncDownloader(QObject):
def __init__(self, url: str, filename: str, parent=None):
super().__init__(parent)
self.net_mgr = QNetworkAccessManager()
self.req = QNetworkRequest(QUrl(url))
self.fetch_task: Optional[QNetworkReply] = None
self.data: Optional[QByteArray] = None
self.file = QFile(filename)
def start_fetch(self):
self.fetch_task = self.net_mgr.get(self.req)
self.fetch_task.downloadProgress.connect(self.on_progress)
self.fetch_task.finished.connect(self.on_finished)
def on_progress(self, bytes_received: int, bytes_total: int):
print(f"bytes received {bytes_received} (total {bytes_total})")
def on_finished(self):
print("finished")
self.data = self.fetch_task.readAll()
if not self.file.open(QFile.WriteOnly):
raise IOError(f"Unable to write to {self.file.fileName}")
self.file.write(self.data)
self.file.close()
print(f"file written to {self.file.fileName()}")
if __name__ == '__main__':
from pathlib import Path
from PyQt5.QtWidgets import QApplication
dl_path = os.path.join(str(Path.home()), "test_dl")
os.makedirs(dl_path, exist_ok=True)
app = QApplication([])
downloader = AsyncDownloader(
"https://github.com/PiRK/Electrum-ABC-Build-Tools/releases/download/v1.0/tor-linux",
os.path.join(dl_path, "tor")
)
downloader.start_fetch()
app.exec_()
我收到的错误(或警告?)包括:
qt.network.ssl: QSslSocket: cannot resolve EVP_PKEY_base_id
qt.network.ssl: QSslSocket: cannot resolve SSL_get_peer_certificate
qt.network.ssl: QSslSocket: cannot call unresolved function SSL_get_peer_certificate
bytes received 0 (total 0)
finished
file written to /home/myname/test_dl/tor
写入的文件为空。
我尝试在self.net_mgr = ....
后面添加以下行:
parsed_url = urllib.parse.urlparse(url)
if parsed_url.scheme == "https":
self.net_mgr.connectToHostEncrypted(parsed_url.hostname)
这没有帮助。
使用wget
时下载工作正常:
$ wget "https://github.com/PiRK/Electrum-ABC-Build-Tools/releases/download/v1.0/tor-linux"
...
tor-linux 100%[=============================================================================================>] 15,34M 985KB/s in 16s
2023-02-16 16:36:51 (969 KB/s) - ‘tor-linux’ saved [16090880/16090880]
2条答案
按热度按时间bnlyeluc1#
在
QNetworkAccessManager
无法支持HTTPS之后,我使用了基于Python的multiprocessing
标准库和requests
库(不是stdlib,但urllib.request
的官方Python文档推荐)的替代解决方案。唯一的缺点是,我没有得到任何下载进度信息。
下面是一个156 MB文件的输出示例:
8yoxcaq72#