class MyNetworkTest(QMainWindow):
def __init__(self, parent = None):
super().__init__(parent)
self.mywidget = testnetwork.Ui_MainWindow()
self.mywidget.setupUi(self)
self.mywidget.pushButton.clicked.connect(self.requestNetwork)
def replyFinished(self, reply):
pass
def requestNetwork(self):
httpReq = HttpReq()
url = 'http://localhost:8021/api/v1/getDesignTool'
data_dict = {'seqno': '10001'}
httpReq.request(url, data_dict, self.request_success, self.request_error)
import sys
import json
import testnetwork
from PyQt5.QtWidgets import *
from PyQt5.QtNetwork import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class HttpReq(QObject):
def __init__(self):
super().__init__()
self.onSuccess = None
self.onFailed = None
self.m_netAccessManager = QNetworkAccessManager()
self.m_netReply = None
def request(self, httpUrl, sendData, on_success, on_fail):
if self.m_netReply is not None:
self.m_netReply.disconnect()
self.onSuccess = on_success
self.onFailed = on_fail
req = QNetworkRequest(QUrl( httpUrl))
req.setHeader(QNetworkRequest.ContentTypeHeader, "application/x-www-form-urlencoded")
senda = QByteArray()
senda.append(self.convertDict(sendData))
self.m_netAccessManager.finished.connect(self.readData)
self.m_netReply = self.m_netAccessManager.post(req, senda)
# eventloop = QEventLoop()
# eventloop.exec()
# QNetworkReply * postReply = m_pNetManager->post(request, qbt); // post 方式到本地服务器
# connect(postReply, SIGNAL(finished()), this, SLOT(postFileReplyFinished())); // 成功后会有返回响应
# loop->exec();
# self.m_netReply.finished.connect(self.readData)
# self.m_netReply.error.connect(self.requesterr)
def readData(self):
recvData = self.m_netReply.readAll()
print(recvData)
data = bytes.decode(recvData.data(), encoding='utf8')
try:
result = json.loads(data)
self.onSuccess(result)
except Exception as err:
self.onFailed(err)
def requesterr(self, err):
self.onFailed(err)
def convertDict(self, param_dict):
param_str = ""
index = 1
for key, value in param_dict.items():
if index == len(param_dict):
param_str += '%s%s%s' % (key, '=', value)
else:
param_str = '%s%s%s%s' % (key, '=', value, '&')
index += 1
return param_str
发现不在主线程上 self.m_netAccessManager.finished.connect(self.readData) 的回调不会执行 这个 QEventLoop 也不知道如何用,有用过 Pyqt5 开发的朋友提供下文章或者相关代码么,post 请求发文件和数据的相关的,谢谢
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.