本文整理汇总了Python中PyQt5.QtNetwork.QNetworkAccessManager.post方法的典型用法代码示例。如果您正苦于以下问题:Python QNetworkAccessManager.post方法的具体用法?Python QNetworkAccessManager.post怎么用?Python QNetworkAccessManager.post使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtNetwork.QNetworkAccessManager
的用法示例。
在下文中一共展示了QNetworkAccessManager.post方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import post [as 别名]
def post(self, url, data):
if isinstance(data, dict): data = json.dumps(data)
if isinstance(data, str): data = QByteArray(len(data), data)
elif isinstance(data, bytes): data = QByteArray(data)
else:
data = str(data)
data = QByteArray(len(data), data)
return QNetworkAccessManager.post(self, self._getRequest(url), data)
示例2: Fetch
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import post [as 别名]
class Fetch():
data = QtCore.pyqtSignal(dict)
def __init__(self, parent):
self.session = QNetworkAccessManager(parent)
self.cookies = QNetworkCookieJar()
self.parent = parent
self.session.setCookieJar(self.cookies)
def base_handler(self, reply: QNetworkReply):
try:
response = json.loads(str(reply.readAll(), encoding='utf-8'))
status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
except:
self.parent.warn.add_warn("Http解析错误")
return
if reply.error() != QNetworkReply.NoError:
self.handler_error(response, status_code)
else:
self.data.emit(response)
def get(self, url, param=None):
url = QtCore.QUrl(parse_url(url, param))
request = QNetworkRequest(url)
reply = self.session.get(request)
return reply
def post(self, url, param=None, data=None, json=True):
if isinstance(data, dict):
f = ''
for i in data:
f += '{}={}&'.format(i, data[i])
data = f[:-1]
byte_data = QtCore.QByteArray()
byte_data.append(data)
url = QtCore.QUrl(parse_url(url, param))
request = QNetworkRequest(url)
if json:
request.setHeader(QNetworkRequest.ContentTypeHeader, 'application/json')
reply = self.session.post(request, byte_data)
return reply
def handler_error(self, response, status_code):
if isinstance(response, dict):
message = response.get('error', 'unknown')
self.parent.warn.add_warn('网络请求错误,错误码为{},原因为{}'.format(status_code, message))
示例3: HTTPClient
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import post [as 别名]
class HTTPClient(QObject):
"""An HTTP client based on QNetworkAccessManager.
Intended for APIs, automatically decodes data.
Attributes:
_nam: The QNetworkAccessManager used.
_timers: A {QNetworkReply: QTimer} dict.
Signals:
success: Emitted when the operation succeeded.
arg: The received data.
error: Emitted when the request failed.
arg: The error message, as string.
"""
success = pyqtSignal(str)
error = pyqtSignal(str)
def __init__(self, parent=None):
super().__init__(parent)
self._nam = QNetworkAccessManager(self)
self._timers = {}
def post(self, url, data=None):
"""Create a new POST request.
Args:
url: The URL to post to, as QUrl.
data: A dict of data to send.
"""
if data is None:
data = {}
encoded_data = urllib.parse.urlencode(data).encode('utf-8')
request = QNetworkRequest(url)
request.setHeader(QNetworkRequest.ContentTypeHeader,
'application/x-www-form-urlencoded;charset=utf-8')
reply = self._nam.post(request, encoded_data)
self._handle_reply(reply)
def get(self, url):
"""Create a new GET request.
Emits success/error when done.
Args:
url: The URL to access, as QUrl.
"""
request = QNetworkRequest(url)
reply = self._nam.get(request)
self._handle_reply(reply)
def _handle_reply(self, reply):
"""Handle a new QNetworkReply."""
if reply.isFinished():
self.on_reply_finished(reply)
else:
timer = QTimer(self)
timer.setInterval(10000)
timer.timeout.connect(reply.abort)
timer.start()
self._timers[reply] = timer
reply.finished.connect(functools.partial(
self.on_reply_finished, reply))
def on_reply_finished(self, reply):
"""Read the data and finish when the reply finished.
Args:
reply: The QNetworkReply which finished.
"""
timer = self._timers.pop(reply)
if timer is not None:
timer.stop()
timer.deleteLater()
if reply.error() != QNetworkReply.NoError:
self.error.emit(reply.errorString())
return
try:
data = bytes(reply.readAll()).decode('utf-8')
except UnicodeDecodeError:
self.error.emit("Invalid UTF-8 data received in reply!")
return
self.success.emit(data)
示例4: PastebinClient
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import post [as 别名]
class PastebinClient(QObject):
"""A client for http://p.cmpl.cc/ using QNetworkAccessManager.
Attributes:
_nam: The QNetworkAccessManager used.
Class attributes:
API_URL: The base API URL.
Signals:
success: Emitted when the paste succeeded.
arg: The URL of the paste, as string.
error: Emitted when the paste failed.
arg: The error message, as string.
"""
API_URL = 'http://paste.the-compiler.org/api/'
success = pyqtSignal(str)
error = pyqtSignal(str)
def __init__(self, parent=None):
super().__init__(parent)
self._nam = QNetworkAccessManager(self)
def paste(self, name, title, text, parent=None):
"""Paste the text into a pastebin and return the URL.
Args:
name: The username to post as.
title: The post title.
text: The text to post.
parent: The parent paste to reply to.
"""
data = {
'text': text,
'title': title,
'name': name,
}
if parent is not None:
data['reply'] = parent
encoded_data = urllib.parse.urlencode(data).encode('utf-8')
create_url = urllib.parse.urljoin(self.API_URL, 'create')
request = QNetworkRequest(QUrl(create_url))
request.setHeader(QNetworkRequest.ContentTypeHeader,
'application/x-www-form-urlencoded;charset=utf-8')
reply = self._nam.post(request, encoded_data)
if reply.isFinished():
self.on_reply_finished(reply)
else:
reply.finished.connect(functools.partial(
self.on_reply_finished, reply))
def on_reply_finished(self, reply):
"""Read the data and finish when the reply finished.
Args:
reply: The QNetworkReply which finished.
"""
if reply.error() != QNetworkReply.NoError:
self.error.emit(reply.errorString())
return
try:
url = bytes(reply.readAll()).decode('utf-8')
except UnicodeDecodeError:
self.error.emit("Invalid UTF-8 data received in reply!")
return
if url.startswith('http://'):
self.success.emit(url)
else:
self.error.emit("Invalid data received in reply!")
示例5: E5XmlRpcClient
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import post [as 别名]
class E5XmlRpcClient(QObject):
"""
Class implementing a xmlrpc client for Qt.
"""
def __init__(self, url, parent=None):
"""
Constructor
@param url xmlrpc handler URL (string or QUrl)
@param parent parent object (QObject)
"""
super(E5XmlRpcClient, self).__init__(parent)
# attributes for the network objects
self.__networkManager = QNetworkAccessManager(self)
self.__networkManager.proxyAuthenticationRequired.connect(
proxyAuthenticationRequired)
self.__networkManager.finished.connect(self.__replyFinished)
if SSL_AVAILABLE:
self.__sslErrorHandler = E5SslErrorHandler(self)
self.__networkManager.sslErrors.connect(self.__sslErrors)
self.__callmap = {}
self.__request = QNetworkRequest(QUrl(url))
self.__request.setRawHeader(b"User-Agent", b"E5XmlRpcClient/1.0")
self.__request.setHeader(QNetworkRequest.ContentTypeHeader, "text/xml")
def setUrl(self, url):
"""
Public slot to set the xmlrpc handler URL.
@param url xmlrpc handler URL (string or QUrl)
"""
url = QUrl(url)
if url.isValid():
self.__request.setUrl(url)
def call(self, method, args, responseCallback, errorCallback):
"""
Public method to call the remote server.
@param method name of the remote method to be called (string)
@param args tuple of method arguments (tuple)
@param responseCallback method to be called with the returned
result as a tuple (function)
@param errorCallback method to be called in case of an error
with error code and error string (function)
"""
assert isinstance(args, tuple), \
"argument must be tuple or Fault instance"
data = xmlrpc.dumps(args, method).encode("utf-8")
reply = self.__networkManager.post(
self.__request, QByteArray(data))
self.__callmap[reply] = (responseCallback, errorCallback)
def abort(self):
"""
Public method to abort all calls.
"""
for reply in list(self.__callmap):
if reply.isRunning():
reply.abort()
def __sslErrors(self, reply, errors):
"""
Private slot to handle SSL errors.
@param reply reference to the reply object (QNetworkReply)
@param errors list of SSL errors (list of QSslError)
"""
ignored = self.__sslErrorHandler.sslErrorsReply(reply, errors)[0]
if ignored == E5SslErrorHandler.NotIgnored and reply in self.__callmap:
self.__callmap[reply][1](xmlrpc.TRANSPORT_ERROR, self.tr(
"SSL Error"))
def __replyFinished(self, reply):
"""
Private slot handling the receipt of a reply.
@param reply reference to the finished reply (QNetworkReply)
"""
if reply not in self.__callmap:
return
if reply.error() != QNetworkReply.NoError:
self.__callmap[reply][1](xmlrpc.TRANSPORT_ERROR,
reply.errorString())
else:
data = bytes(reply.readAll()).decode("utf-8")
try:
data = xmlrpc.loads(data)[0]
self.__callmap[reply][0](data)
except xmlrpc.Fault as fault:
self.__callmap[reply][1](fault.faultCode, fault.faultString)
reply.deleteLater()
del self.__callmap[reply]
示例6: DiscoverOctoPrintAction
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import post [as 别名]
#.........这里部分代码省略.........
def discoveredInstances(self) -> List[Any]:
if self._network_plugin:
instances = list(self._network_plugin.getInstances().values())
instances.sort(key = lambda k: k.name)
return instances
else:
return []
@pyqtSlot(str)
def setInstanceId(self, key: str) -> None:
global_container_stack = self._application.getGlobalContainerStack()
if global_container_stack:
global_container_stack.setMetaDataEntry("octoprint_id", key)
if self._network_plugin:
# Ensure that the connection states are refreshed.
self._network_plugin.reCheckConnections()
@pyqtSlot(result = str)
def getInstanceId(self) -> str:
global_container_stack = self._application.getGlobalContainerStack()
if not global_container_stack:
return ""
return global_container_stack.getMetaDataEntry("octoprint_id", "")
@pyqtSlot(str, str, str, str)
def requestApiKey(self, instance_id: str, base_url: str, basic_auth_username: str = "", basic_auth_password: str = "") -> None:
## Request appkey
self._appkey_instance_id = instance_id
self._appkey_request = self._createRequest(QUrl(base_url + "plugin/appkeys/request"), basic_auth_username, basic_auth_password)
self._appkey_request.setRawHeader(b"Content-Type", b"application/json")
data = json.dumps({"app": "Cura"})
self._appkey_reply = self._network_manager.post(self._appkey_request, data.encode())
@pyqtSlot()
def cancelApiKeyRequest(self) -> None:
if self._appkey_reply:
self._appkey_reply.abort()
self._appkey_reply = None
self._appkey_request = None # type: Optional[QNetworkRequest]
self._appkey_poll_timer.stop()
def _pollApiKey(self) -> None:
if not self._appkey_request:
return
self._appkey_reply = self._network_manager.get(self._appkey_request)
@pyqtSlot(str, str, str)
def probeAppKeySupport(self, base_url: str, basic_auth_username: str = "", basic_auth_password: str = "") -> None:
self._appkeys_supported = False
self.appKeysSupportedChanged.emit()
appkey_probe_request = self._createRequest(QUrl(base_url + "plugin/appkeys/probe"), basic_auth_username, basic_auth_password)
self._appkey_request = self._network_manager.get(appkey_probe_request)
@pyqtSlot(str, str, str, str)
def testApiKey(self, base_url: str, api_key: str, basic_auth_username: str = "", basic_auth_password: str = "") -> None:
self._instance_responded = False
self._instance_api_key_accepted = False
self._instance_supports_sd = False
self._instance_supports_camera = False
self.selectedInstanceSettingsChanged.emit()
示例7: Ycm
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import post [as 别名]
#.........这里部分代码省略.........
def _hmacDigest(self, msg):
return hmac.new(self.secret, msg, hashlib.sha256).digest()
def _sign(self, verb, path, body=b''):
digests = [self._hmacDigest(part) for part in [verb, path, body]]
return self._hmacDigest(b''.join(digests))
def _doGet(self, path):
url = urlunsplit(('http', self.addr, path, '', ''))
sig = self._sign(b'GET', path.encode('utf-8'), b'')
headers = {
HMAC_HEADER: b64encode(sig)
}
request = QNetworkRequest(QUrl(url))
for hname in headers:
request.setRawHeader(hname, headers[hname])
reply = self.network.get(request)
return reply
def _doPost(self, path, **params):
url = urlunsplit(('http', self.addr, path, '', ''))
body = json.dumps(params)
sig = self._sign(b'POST', path.encode('utf-8'), body.encode('utf-8'))
headers = {
HMAC_HEADER: b64encode(sig),
'Content-Type': 'application/json'
}
request = QNetworkRequest(QUrl(url))
for hname in headers:
request.setRawHeader(hname, headers[hname])
reply = self.network.post(request, body)
return reply
def ping(self):
def handleReply():
self.checkReply(reply)
if not self._ready:
self._ready = True
self.pingTimer.start(60000)
self.ready.emit()
reply = self._doGet('/healthy')
reply.finished.connect(handleReply)
reply.finished.connect(reply.deleteLater)
def start(self):
if not self.port:
self.port = generate_port()
self.addr = 'localhost:%s' % self.port
path = self.makeConfig()
_, outlogpath = tempfile.mkstemp(prefix='eye-ycm', suffix='.out.log')
_, errlogpath = tempfile.mkstemp(prefix='eye-ycm', suffix='.err.log')
LOGGER.info('ycmd will log to %r and %r', outlogpath, errlogpath)
cmd = (self.YCMD_CMD +
[
'--idle_suicide_seconds', str(self.IDLE_SUICIDE),
'--port', str(self.port),
'--options_file', path,
'--stdout', outlogpath,
'--stderr', errlogpath,
])
示例8: OctoPrintOutputDevice
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import post [as 别名]
class OctoPrintOutputDevice(PrinterOutputDevice):
def __init__(self, key, address, properties):
super().__init__(key)
self._address = address
self._key = key
self._properties = properties # Properties dict as provided by zero conf
self._gcode = None
## Todo: Hardcoded value now; we should probably read this from the machine definition and octoprint.
self._num_extruders = 1
self._hotend_temperatures = [0] * self._num_extruders
self._target_hotend_temperatures = [0] * self._num_extruders
self._api_version = "1"
self._api_prefix = "/api/"
self._api_header = "X-Api-Key"
self._api_key = None
self.setName(key)
self.setShortDescription(i18n_catalog.i18nc("@action:button", "Print with OctoPrint"))
self.setDescription(i18n_catalog.i18nc("@properties:tooltip", "Print with OctoPrint"))
self.setIconName("print")
# QNetwork manager needs to be created in advance. If we don't it can happen that it doesn't correctly
# hook itself into the event loop, which results in events never being fired / done.
self._manager = QNetworkAccessManager()
self._manager.finished.connect(self._onFinished)
## Hack to ensure that the qt networking stuff isn't garbage collected (unless we want it to)
self._printer_request = None
self._printer_reply = None
self._print_job_request = None
self._print_job_reply = None
self._image_request = None
self._image_reply = None
self._post_request = None
self._post_reply = None
self._post_multi_part = None
self._post_part = None
self._job_request = None
self._job_reply = None
self._progress_message = None
self._error_message = None
self._update_timer = QTimer()
self._update_timer.setInterval(2000) # TODO; Add preference for update interval
self._update_timer.setSingleShot(False)
self._update_timer.timeout.connect(self._update)
self._camera_timer = QTimer()
self._camera_timer.setInterval(500) # Todo: Add preference for camera update interval
self._camera_timer.setSingleShot(False)
self._camera_timer.timeout.connect(self._update_camera)
self._camera_image_id = 0
self._camera_image = QImage()
def getProperties(self):
return self._properties
## Get the unique key of this machine
# \return key String containing the key of the machine.
@pyqtSlot(result = str)
def getKey(self):
return self._key
## Set the API key of this OctoPrint instance
def setApiKey(self, api_key):
self._api_key = api_key
## Name of the printer (as returned from the zeroConf properties)
@pyqtProperty(str, constant = True)
def name(self):
return self._key
## Version (as returned from the zeroConf properties)
@pyqtProperty(str, constant=True)
def octoprintVersion(self):
return self._properties.get(b"version", b"").decode("utf-8")
## IPadress of this printer
@pyqtProperty(str, constant=True)
def ipAddress(self):
return self._address
def _update_camera(self):
## Request new image
url = QUrl("http://" + self._address + ":8080/?action=snapshot")
self._image_request = QNetworkRequest(url)
self._image_reply = self._manager.get(self._image_request)
def _update(self):
#.........这里部分代码省略.........
示例9: __init__
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import post [as 别名]
class CloudApiClient:
# The cloud URL to use for this remote cluster.
ROOT_PATH = UltimakerCloudAuthentication.CuraCloudAPIRoot
CLUSTER_API_ROOT = "{}/connect/v1".format(ROOT_PATH)
CURA_API_ROOT = "{}/cura/v1".format(ROOT_PATH)
## Initializes a new cloud API client.
# \param account: The user's account object
# \param on_error: The callback to be called whenever we receive errors from the server.
def __init__(self, account: Account, on_error: Callable[[List[CloudError]], None]) -> None:
super().__init__()
self._manager = QNetworkAccessManager()
self._account = account
self._on_error = on_error
self._upload = None # type: Optional[ToolPathUploader]
# In order to avoid garbage collection we keep the callbacks in this list.
self._anti_gc_callbacks = [] # type: List[Callable[[], None]]
## Gets the account used for the API.
@property
def account(self) -> Account:
return self._account
## Retrieves all the clusters for the user that is currently logged in.
# \param on_finished: The function to be called after the result is parsed.
def getClusters(self, on_finished: Callable[[List[CloudClusterResponse]], Any]) -> None:
url = "{}/clusters".format(self.CLUSTER_API_ROOT)
reply = self._manager.get(self._createEmptyRequest(url))
self._addCallback(reply, on_finished, CloudClusterResponse)
## Retrieves the status of the given cluster.
# \param cluster_id: The ID of the cluster.
# \param on_finished: The function to be called after the result is parsed.
def getClusterStatus(self, cluster_id: str, on_finished: Callable[[CloudClusterStatus], Any]) -> None:
url = "{}/clusters/{}/status".format(self.CLUSTER_API_ROOT, cluster_id)
reply = self._manager.get(self._createEmptyRequest(url))
self._addCallback(reply, on_finished, CloudClusterStatus)
## Requests the cloud to register the upload of a print job mesh.
# \param request: The request object.
# \param on_finished: The function to be called after the result is parsed.
def requestUpload(self, request: CloudPrintJobUploadRequest, on_finished: Callable[[CloudPrintJobResponse], Any]
) -> None:
url = "{}/jobs/upload".format(self.CURA_API_ROOT)
body = json.dumps({"data": request.toDict()})
reply = self._manager.put(self._createEmptyRequest(url), body.encode())
self._addCallback(reply, on_finished, CloudPrintJobResponse)
## Uploads a print job tool path to the cloud.
# \param print_job: The object received after requesting an upload with `self.requestUpload`.
# \param mesh: The tool path data to be uploaded.
# \param on_finished: The function to be called after the upload is successful.
# \param on_progress: A function to be called during upload progress. It receives a percentage (0-100).
# \param on_error: A function to be called if the upload fails.
def uploadToolPath(self, print_job: CloudPrintJobResponse, mesh: bytes, on_finished: Callable[[], Any],
on_progress: Callable[[int], Any], on_error: Callable[[], Any]):
self._upload = ToolPathUploader(self._manager, print_job, mesh, on_finished, on_progress, on_error)
self._upload.start()
# Requests a cluster to print the given print job.
# \param cluster_id: The ID of the cluster.
# \param job_id: The ID of the print job.
# \param on_finished: The function to be called after the result is parsed.
def requestPrint(self, cluster_id: str, job_id: str, on_finished: Callable[[CloudPrintResponse], Any]) -> None:
url = "{}/clusters/{}/print/{}".format(self.CLUSTER_API_ROOT, cluster_id, job_id)
reply = self._manager.post(self._createEmptyRequest(url), b"")
self._addCallback(reply, on_finished, CloudPrintResponse)
## We override _createEmptyRequest in order to add the user credentials.
# \param url: The URL to request
# \param content_type: The type of the body contents.
def _createEmptyRequest(self, path: str, content_type: Optional[str] = "application/json") -> QNetworkRequest:
request = QNetworkRequest(QUrl(path))
if content_type:
request.setHeader(QNetworkRequest.ContentTypeHeader, content_type)
access_token = self._account.accessToken
if access_token:
request.setRawHeader(b"Authorization", "Bearer {}".format(access_token).encode())
return request
## Parses the given JSON network reply into a status code and a dictionary, handling unexpected errors as well.
# \param reply: The reply from the server.
# \return A tuple with a status code and a dictionary.
@staticmethod
def _parseReply(reply: QNetworkReply) -> Tuple[int, Dict[str, Any]]:
status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
try:
response = bytes(reply.readAll()).decode()
return status_code, json.loads(response)
except (UnicodeDecodeError, JSONDecodeError, ValueError) as err:
error = CloudError(code=type(err).__name__, title=str(err), http_code=str(status_code),
id=str(time()), http_status="500")
Logger.logException("e", "Could not parse the stardust response: %s", error.toDict())
return status_code, {"errors": [error.toDict()]}
## Parses the given models and calls the correct callback depending on the result.
# \param response: The response from the server, after being converted to a dict.
# \param on_finished: The callback in case the response is successful.
# \param model_class: The type of the model to convert the response to. It may either be a single record or a list.
#.........这里部分代码省略.........