本文整理汇总了Python中PyQt5.QtNetwork.QNetworkAccessManager.get方法的典型用法代码示例。如果您正苦于以下问题:Python QNetworkAccessManager.get方法的具体用法?Python QNetworkAccessManager.get怎么用?Python QNetworkAccessManager.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtNetwork.QNetworkAccessManager
的用法示例。
在下文中一共展示了QNetworkAccessManager.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Fetch
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import get [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))
示例2: Application
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import get [as 别名]
class Application(QObject):
"""
Managing core application datas :
Accounts list and general configuration
Saving and loading the application state
"""
loading_progressed = pyqtSignal(int, int)
version_requested = pyqtSignal()
def __init__(self, argv, qapp):
"""
Create a new "cutecoin" application
:param argv: The argv parameters of the call
"""
super().__init__()
self.qapp = qapp
self.accounts = {}
self.current_account = None
self.monitor = None
self.available_version = (True, __version__, "")
config.parse_arguments(argv)
self._network_manager = QNetworkAccessManager()
self._network_manager.finished.connect(self.read_available_version)
self.preferences = {"account": "", "lang": "en_GB", "ref": 0}
self.load()
self.switch_language()
def switch_language(self):
translator = QTranslator(self.qapp)
logging.debug("Loading translations")
locale = self.preferences["lang"]
QLocale.setDefault(QLocale(locale))
if translator.load(":/i18n/{0}".format(locale)):
if QCoreApplication.installTranslator(translator):
logging.debug("Loaded i18n/{0}".format(locale))
else:
logging.debug("Couldn't load translation")
def get_account(self, name):
"""
Load an account then return it
:param str name: The account name
:return: The loaded account if it's a success, else return None
"""
self.load_account(name)
if name in self.accounts.keys():
return self.accounts[name]
else:
return None
def create_account(self, name):
"""
Create a new account from its name
:param str name: The account name
:return: The new account
:raise: NameAlreadyExists if the account name is already used locally
"""
for a in self.accounts:
if a == name:
raise NameAlreadyExists(a)
account = Account.create(name)
return account
def add_account(self, account):
self.accounts[account.name] = account
def delete_account(self, account):
"""
Delete an account.
Current account changes to None if it is deleted.
"""
self.accounts.pop(account.name)
if self.current_account == account:
self.current_account = None
with open(config.parameters["data"], "w") as outfile:
json.dump(self.jsonify(), outfile, indent=4, sort_keys=True)
if self.preferences["account"] == account.name:
self.preferences["account"] = ""
self.save_preferences(self.preferences)
def change_current_account(self, account):
"""
Change current account displayed and refresh its cache.
:param account: The account object to display
.. note:: Emits the application pyqtSignal loading_progressed
during cache refresh
"""
def progressing(value, maximum):
self.loading_progressed.emit(value, maximum)
#.........这里部分代码省略.........
示例3: downloadManager
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import get [as 别名]
class downloadManager(QObject):
manager = None
currentDownload = None
reply = None
url = None
result = None
filename = None
dir_ = None
url_ = None
def __init__(self):
super(downloadManager, self).__init__()
self.manager = QNetworkAccessManager()
self.currentDownload = []
self.manager.finished.connect(self.downloadFinished)
def setLE(self, filename, dir_, urllineedit):
self.filename = filename
self.dir_ = dir_
self.url_ = urllineedit
def doDownload(self):
request = QNetworkRequest(QUrl("%s/%s/%s" % (self.url_.text(), self.dir_, self.filename)))
self.reply = self.manager.get(request)
# self.reply.sslErrors.connect(self.sslErrors)
self.currentDownload.append(self.reply)
def saveFileName(self, url):
path = url.path()
basename = QFileInfo(path).fileName()
if not basename:
basename = "download"
if QFile.exists(basename):
i = 0
basename = basename + "."
while QFile.exists("%s%s" % (basename, i)):
i = i + 1
basename = "%s%s" % (basename, i)
return basename
def saveToDisk(self, filename, data):
fi = "%s/%s" % (self.dir_, filename)
if not os.path.exists(self.dir_):
os.makedirs(self.dir_)
file = QFile(fi)
if not file.open(QIODevice.WriteOnly):
return False
file.write(data.readAll())
file.close()
return True
def isHttpRedirect(self, reply):
statusCode = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
return statusCode in [301, 302, 303, 305, 307, 308]
@QtCore.pyqtSlot(QNetworkReply)
def downloadFinished(self, reply):
url = reply.url()
if not reply.error():
if not self.isHttpRedirect(reply):
filename = self.saveFileName(url)
filename = filename.replace(":", "")
self.saveToDisk(filename, reply)
self.result = "%s ---> %s/%s" % (url, self.dir_, filename)
else:
self.result = "Redireccionado ... :("
else:
self.result = reply.errorString()
示例4: PACFetcher
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import get [as 别名]
class PACFetcher(QObject):
"""Asynchronous fetcher of PAC files."""
finished = pyqtSignal()
def __init__(self, url, parent=None):
"""Resolve a PAC proxy from URL.
Args:
url: QUrl of a PAC proxy.
"""
super().__init__(parent)
pac_prefix = "pac+"
assert url.scheme().startswith(pac_prefix)
url.setScheme(url.scheme()[len(pac_prefix):])
self._pac_url = url
self._manager = QNetworkAccessManager()
self._manager.setProxy(QNetworkProxy(QNetworkProxy.NoProxy))
self._reply = self._manager.get(QNetworkRequest(url))
self._reply.finished.connect(self._finish)
self._pac = None
self._error_message = None
@pyqtSlot()
def _finish(self):
if self._reply.error() != QNetworkReply.NoError:
error = "Can't fetch PAC file from URL, error code {}: {}"
self._error_message = error.format(
self._reply.error(), self._reply.errorString())
log.network.error(self._error_message)
else:
try:
pacscript = bytes(self._reply.readAll()).decode("utf-8")
except UnicodeError as e:
error = "Invalid encoding of a PAC file: {}"
self._error_message = error.format(e)
log.network.exception(self._error_message)
try:
self._pac = PACResolver(pacscript)
log.network.debug("Successfully evaluated PAC file.")
except EvalProxyError as e:
error = "Error in PAC evaluation: {}"
self._error_message = error.format(e)
log.network.exception(self._error_message)
self._manager = None
self._reply = None
self.finished.emit()
def _wait(self):
"""Wait until a reply from the remote server is received."""
if self._manager is not None:
loop = qtutils.EventLoop()
self.finished.connect(loop.quit)
loop.exec_()
def fetch_error(self):
"""Check if PAC script is successfully fetched.
Return None iff PAC script is downloaded and evaluated successfully,
error string otherwise.
"""
self._wait()
return self._error_message
def resolve(self, query):
"""Resolve a query via PAC.
Args: QNetworkProxyQuery.
Return a list of QNetworkProxy objects in order of preference.
"""
self._wait()
from_file = self._pac_url.scheme() == 'file'
try:
return self._pac.resolve(query, from_file=from_file)
except (EvalProxyError, ParseProxyError) as e:
log.network.exception("Error in PAC resolution: {}.".format(e))
# .invalid is guaranteed to be inaccessible in RFC 6761.
# Port 9 is for DISCARD protocol -- DISCARD servers act like
# /dev/null.
# Later NetworkManager.createRequest will detect this and display
# an error message.
error_host = "pac-resolve-error.qutebrowser.invalid"
return [QNetworkProxy(QNetworkProxy.HttpProxy, error_host, 9)]
示例5: NetworkMJPGImage
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import get [as 别名]
class NetworkMJPGImage(QQuickPaintedItem):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self._stream_buffer = QByteArray()
self._stream_buffer_start_index = -1
self._network_manager = None # type: QNetworkAccessManager
self._image_request = None # type: QNetworkRequest
self._image_reply = None # type: QNetworkReply
self._image = QImage()
self._image_rect = QRect()
self._source_url = QUrl()
self._started = False
self._mirror = False
self.setAntialiasing(True)
## Ensure that close gets called when object is destroyed
def __del__(self) -> None:
self.stop()
def paint(self, painter: "QPainter") -> None:
if self._mirror:
painter.drawImage(self.contentsBoundingRect(), self._image.mirrored())
return
painter.drawImage(self.contentsBoundingRect(), self._image)
def setSourceURL(self, source_url: "QUrl") -> None:
self._source_url = source_url
self.sourceURLChanged.emit()
if self._started:
self.start()
def getSourceURL(self) -> "QUrl":
return self._source_url
sourceURLChanged = pyqtSignal()
source = pyqtProperty(QUrl, fget = getSourceURL, fset = setSourceURL, notify = sourceURLChanged)
def setMirror(self, mirror: bool) -> None:
if mirror == self._mirror:
return
self._mirror = mirror
self.mirrorChanged.emit()
self.update()
def getMirror(self) -> bool:
return self._mirror
mirrorChanged = pyqtSignal()
mirror = pyqtProperty(bool, fget = getMirror, fset = setMirror, notify = mirrorChanged)
imageSizeChanged = pyqtSignal()
@pyqtProperty(int, notify = imageSizeChanged)
def imageWidth(self) -> int:
return self._image.width()
@pyqtProperty(int, notify = imageSizeChanged)
def imageHeight(self) -> int:
return self._image.height()
@pyqtSlot()
def start(self) -> None:
self.stop() # Ensure that previous requests (if any) are stopped.
if not self._source_url:
Logger.log("w", "Unable to start camera stream without target!")
return
self._started = True
self._image_request = QNetworkRequest(self._source_url)
if self._network_manager is None:
self._network_manager = QNetworkAccessManager()
self._image_reply = self._network_manager.get(self._image_request)
self._image_reply.downloadProgress.connect(self._onStreamDownloadProgress)
@pyqtSlot()
def stop(self) -> None:
self._stream_buffer = QByteArray()
self._stream_buffer_start_index = -1
if self._image_reply:
try:
try:
self._image_reply.downloadProgress.disconnect(self._onStreamDownloadProgress)
except Exception:
pass
if not self._image_reply.isFinished():
self._image_reply.close()
except Exception as e: # RuntimeError
#.........这里部分代码省略.........
示例6: NetworkPrinterOutputDevicePlugin
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import get [as 别名]
class NetworkPrinterOutputDevicePlugin(OutputDevicePlugin):
def __init__(self):
super().__init__()
self._zero_conf = None
self._browser = None
self._printers = {}
self._api_version = "1"
self._api_prefix = "/api/v" + self._api_version + "/"
self._network_manager = QNetworkAccessManager()
self._network_manager.finished.connect(self._onNetworkRequestFinished)
# List of old printer names. This is used to ensure that a refresh of zeroconf does not needlessly forces
# authentication requests.
self._old_printers = []
# Because the model needs to be created in the same thread as the QMLEngine, we use a signal.
self.addPrinterSignal.connect(self.addPrinter)
self.removePrinterSignal.connect(self.removePrinter)
Application.getInstance().globalContainerStackChanged.connect(self.reCheckConnections)
# Get list of manual printers from preferences
self._preferences = Preferences.getInstance()
self._preferences.addPreference("um3networkprinting/manual_instances", "") # A comma-separated list of ip adresses or hostnames
self._manual_instances = self._preferences.getValue("um3networkprinting/manual_instances").split(",")
addPrinterSignal = Signal()
removePrinterSignal = Signal()
printerListChanged = Signal()
## Start looking for devices on network.
def start(self):
self.startDiscovery()
def startDiscovery(self):
self.stop()
if self._browser:
self._browser.cancel()
self._browser = None
self._old_printers = [printer_name for printer_name in self._printers]
self._printers = {}
self.printerListChanged.emit()
# After network switching, one must make a new instance of Zeroconf
# On windows, the instance creation is very fast (unnoticable). Other platforms?
self._zero_conf = Zeroconf()
self._browser = ServiceBrowser(self._zero_conf, u'_ultimaker._tcp.local.', [self._onServiceChanged])
# Look for manual instances from preference
for address in self._manual_instances:
if address:
self.addManualPrinter(address)
def addManualPrinter(self, address):
if address not in self._manual_instances:
self._manual_instances.append(address)
self._preferences.setValue("um3networkprinting/manual_instances", ",".join(self._manual_instances))
name = address
instance_name = "manual:%s" % address
properties = { b"name": name.encode("utf-8"), b"manual": b"true", b"incomplete": b"true" }
if instance_name not in self._printers:
# Add a preliminary printer instance
self.addPrinter(instance_name, address, properties)
self.checkManualPrinter(address)
def removeManualPrinter(self, key, address = None):
if key in self._printers:
if not address:
address = self._printers[key].ipAddress
self.removePrinter(key)
if address in self._manual_instances:
self._manual_instances.remove(address)
self._preferences.setValue("um3networkprinting/manual_instances", ",".join(self._manual_instances))
def checkManualPrinter(self, address):
# Check if a printer exists at this address
# If a printer responds, it will replace the preliminary printer created above
url = QUrl("http://" + address + self._api_prefix + "system")
name_request = QNetworkRequest(url)
self._network_manager.get(name_request)
## Handler for all requests that have finished.
def _onNetworkRequestFinished(self, reply):
reply_url = reply.url().toString()
status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
if reply.operation() == QNetworkAccessManager.GetOperation:
if "system" in reply_url: # Name returned from printer.
if status_code == 200:
system_info = json.loads(bytes(reply.readAll()).decode("utf-8"))
address = reply.url().host()
name = ("%s (%s)" % (system_info["name"], address))
instance_name = "manual:%s" % address
properties = { b"name": name.encode("utf-8"), b"firmware_version": system_info["firmware"].encode("utf-8"), b"manual": b"true" }
if instance_name in self._printers:
#.........这里部分代码省略.........
示例7: Toolbox
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import get [as 别名]
class Toolbox(QObject, Extension):
DEFAULT_CLOUD_API_ROOT = "https://api.ultimaker.com" # type: str
DEFAULT_CLOUD_API_VERSION = 1 # type: int
def __init__(self, application: CuraApplication) -> None:
super().__init__()
self._application = application # type: CuraApplication
self._sdk_version = None # type: Optional[Union[str, int]]
self._cloud_api_version = None # type: Optional[int]
self._cloud_api_root = None # type: Optional[str]
self._api_url = None # type: Optional[str]
# Network:
self._download_request = None # type: Optional[QNetworkRequest]
self._download_reply = None # type: Optional[QNetworkReply]
self._download_progress = 0 # type: float
self._is_downloading = False # type: bool
self._network_manager = None # type: Optional[QNetworkAccessManager]
self._request_headers = [] # type: List[Tuple[bytes, bytes]]
self._updateRequestHeader()
self._request_urls = {} # type: Dict[str, QUrl]
self._to_update = [] # type: List[str] # Package_ids that are waiting to be updated
self._old_plugin_ids = set() # type: Set[str]
self._old_plugin_metadata = dict() # type: Dict[str, Dict[str, Any]]
# The responses as given by the server parsed to a list.
self._server_response_data = {
"authors": [],
"packages": []
} # type: Dict[str, List[Any]]
# Models:
self._models = {
"authors": AuthorsModel(self),
"packages": PackagesModel(self),
} # type: Dict[str, Union[AuthorsModel, PackagesModel]]
self._plugins_showcase_model = PackagesModel(self)
self._plugins_available_model = PackagesModel(self)
self._plugins_installed_model = PackagesModel(self)
self._materials_showcase_model = AuthorsModel(self)
self._materials_available_model = AuthorsModel(self)
self._materials_installed_model = PackagesModel(self)
self._materials_generic_model = PackagesModel(self)
# These properties are for keeping track of the UI state:
# ----------------------------------------------------------------------
# View category defines which filter to use, and therefore effectively
# which category is currently being displayed. For example, possible
# values include "plugin" or "material", but also "installed".
self._view_category = "plugin" # type: str
# View page defines which type of page layout to use. For example,
# possible values include "overview", "detail" or "author".
self._view_page = "loading" # type: str
# Active package refers to which package is currently being downloaded,
# installed, or otherwise modified.
self._active_package = None # type: Optional[Dict[str, Any]]
self._dialog = None # type: Optional[QObject]
self._confirm_reset_dialog = None # type: Optional[QObject]
self._resetUninstallVariables()
self._restart_required = False # type: bool
# variables for the license agreement dialog
self._license_dialog_plugin_name = "" # type: str
self._license_dialog_license_content = "" # type: str
self._license_dialog_plugin_file_location = "" # type: str
self._restart_dialog_message = "" # type: str
self._application.initializationFinished.connect(self._onAppInitialized)
self._application.getCuraAPI().account.loginStateChanged.connect(self._updateRequestHeader)
# Signals:
# --------------------------------------------------------------------------
# Downloading changes
activePackageChanged = pyqtSignal()
onDownloadProgressChanged = pyqtSignal()
onIsDownloadingChanged = pyqtSignal()
restartRequiredChanged = pyqtSignal()
installChanged = pyqtSignal()
enabledChanged = pyqtSignal()
# UI changes
viewChanged = pyqtSignal()
detailViewChanged = pyqtSignal()
filterChanged = pyqtSignal()
metadataChanged = pyqtSignal()
showLicenseDialog = pyqtSignal()
uninstallVariablesChanged = pyqtSignal()
def _updateRequestHeader(self):
self._request_headers = [
#.........这里部分代码省略.........
示例8: HttpWindow
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import get [as 别名]
class HttpWindow(QDialog):
def __init__(self, parent=None):
super(HttpWindow, self).__init__(parent)
self.url = QUrl()
self.qnam = QNetworkAccessManager()
self.reply = None
self.outFile = None
self.httpGetId = 0
self.httpRequestAborted = False
self.urlLineEdit = QLineEdit('https://www.qt.io')
urlLabel = QLabel("&URL:")
urlLabel.setBuddy(self.urlLineEdit)
self.statusLabel = QLabel(
"Please enter the URL of a file you want to download.")
self.statusLabel.setWordWrap(True)
self.downloadButton = QPushButton("Download")
self.downloadButton.setDefault(True)
self.quitButton = QPushButton("Quit")
self.quitButton.setAutoDefault(False)
buttonBox = QDialogButtonBox()
buttonBox.addButton(self.downloadButton, QDialogButtonBox.ActionRole)
buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole)
self.progressDialog = QProgressDialog(self)
self.urlLineEdit.textChanged.connect(self.enableDownloadButton)
self.qnam.authenticationRequired.connect(
self.slotAuthenticationRequired)
self.qnam.sslErrors.connect(self.sslErrors)
self.progressDialog.canceled.connect(self.cancelDownload)
self.downloadButton.clicked.connect(self.downloadFile)
self.quitButton.clicked.connect(self.close)
topLayout = QHBoxLayout()
topLayout.addWidget(urlLabel)
topLayout.addWidget(self.urlLineEdit)
mainLayout = QVBoxLayout()
mainLayout.addLayout(topLayout)
mainLayout.addWidget(self.statusLabel)
mainLayout.addWidget(buttonBox)
self.setLayout(mainLayout)
self.setWindowTitle("HTTP")
self.urlLineEdit.setFocus()
def startRequest(self, url):
self.reply = self.qnam.get(QNetworkRequest(url))
self.reply.finished.connect(self.httpFinished)
self.reply.readyRead.connect(self.httpReadyRead)
self.reply.downloadProgress.connect(self.updateDataReadProgress)
def downloadFile(self):
self.url = QUrl(self.urlLineEdit.text())
fileInfo = QFileInfo(self.url.path())
fileName = fileInfo.fileName()
if not fileName:
fileName = 'index.html'
if QFile.exists(fileName):
ret = QMessageBox.question(self, "HTTP",
"There already exists a file called %s in the current "
"directory. Overwrite?" % fileName,
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if ret == QMessageBox.No:
return
QFile.remove(fileName)
self.outFile = QFile(fileName)
if not self.outFile.open(QIODevice.WriteOnly):
QMessageBox.information(self, "HTTP",
"Unable to save the file %s: %s." % (fileName, self.outFile.errorString()))
self.outFile = None
return
self.progressDialog.setWindowTitle("HTTP")
self.progressDialog.setLabelText("Downloading %s." % fileName)
self.downloadButton.setEnabled(False)
self.httpRequestAborted = False
self.startRequest(self.url)
def cancelDownload(self):
self.statusLabel.setText("Download canceled.")
self.httpRequestAborted = True
if self.reply is not None:
self.reply.abort()
self.downloadButton.setEnabled(True)
def httpFinished(self):
if self.httpRequestAborted:
if self.outFile is not None:
#.........这里部分代码省略.........
示例9: NetworkCamera
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import get [as 别名]
class NetworkCamera(QObject):
newImage = pyqtSignal()
def __init__(self, target = None, parent = None):
super().__init__(parent)
self._stream_buffer = b""
self._stream_buffer_start_index = -1
self._manager = None
self._image_request = None
self._image_reply = None
self._image = QImage()
self._image_id = 0
self._target = target
self._started = False
@pyqtSlot(str)
def setTarget(self, target):
restart_required = False
if self._started:
self.stop()
restart_required = True
self._target = target
if restart_required:
self.start()
@pyqtProperty(QUrl, notify=newImage)
def latestImage(self):
self._image_id += 1
# There is an image provider that is called "camera". In order to ensure that the image qml object, that
# requires a QUrl to function, updates correctly we add an increasing number. This causes to see the QUrl
# as new (instead of relying on cached version and thus forces an update.
temp = "image://camera/" + str(self._image_id)
return QUrl(temp, QUrl.TolerantMode)
@pyqtSlot()
def start(self):
# Ensure that previous requests (if any) are stopped.
self.stop()
if self._target is None:
Logger.log("w", "Unable to start camera stream without target!")
return
self._started = True
url = QUrl(self._target)
self._image_request = QNetworkRequest(url)
if self._manager is None:
self._manager = QNetworkAccessManager()
self._image_reply = self._manager.get(self._image_request)
self._image_reply.downloadProgress.connect(self._onStreamDownloadProgress)
@pyqtSlot()
def stop(self):
self._stream_buffer = b""
self._stream_buffer_start_index = -1
if self._image_reply:
try:
# disconnect the signal
try:
self._image_reply.downloadProgress.disconnect(self._onStreamDownloadProgress)
except Exception:
pass
# abort the request if it's not finished
if not self._image_reply.isFinished():
self._image_reply.close()
except Exception as e: # RuntimeError
pass # It can happen that the wrapped c++ object is already deleted.
self._image_reply = None
self._image_request = None
self._manager = None
self._started = False
def getImage(self):
return self._image
## Ensure that close gets called when object is destroyed
def __del__(self):
self.stop()
def _onStreamDownloadProgress(self, bytes_received, bytes_total):
# An MJPG stream is (for our purpose) a stream of concatenated JPG images.
# JPG images start with the marker 0xFFD8, and end with 0xFFD9
if self._image_reply is None:
return
self._stream_buffer += self._image_reply.readAll()
if len(self._stream_buffer) > 2000000: # No single camera frame should be 2 Mb or larger
Logger.log("w", "MJPEG buffer exceeds reasonable size. Restarting stream...")
self.stop() # resets stream buffer and start index
self.start()
return
if self._stream_buffer_start_index == -1:
#.........这里部分代码省略.........
示例10: Ycm
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import get [as 别名]
#.........这里部分代码省略.........
raise ServerError(status_code, data)
if not self.CHECK_REPLY_SIGNATURE:
return
actual = b64decode(bytes(reply.rawHeader(HMAC_HEADER)))
expected = self._hmacDigest(reply.content)
if not hmac.compare_digest(expected, actual):
raise RuntimeError('Server signature did not match')
def _jsonReply(self, reply):
body = reply.content.decode('utf-8')
return json.loads(body)
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()
示例11: FLNetwork
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import get [as 别名]
class FLNetwork(QtCore.QObject):
url = None
request = None
manager = None
reply = None
finished = QtCore.pyqtSignal()
start = QtCore.pyqtSignal()
data = QtCore.pyqtSignal(str)
dataTransferProgress = QtCore.pyqtSignal(int, int)
def __init__(self, url):
super(FLNetwork, self).__init__()
self.url = url
from PyQt5.QtNetwork import QNetworkRequest, QNetworkAccessManager
self.request = QNetworkRequest()
self.manager = QNetworkAccessManager()
# self.manager.readyRead.connect(self._slotNetworkStart)
self.manager.finished['QNetworkReply*'].connect(self._slotNetworkFinished)
# self.data.connect(self._slotNetWorkData)
# self.dataTransferProgress.connect(self._slotNetworkProgress)
@decorators.BetaImplementation
def get(self, location):
self.request.setUrl(QtCore.QUrl("%s%s" % (self.url, location)))
self.reply = self.manager.get(self.request)
try:
self.reply.uploadProgress.disconnect(self._slotNetworkProgress)
self.reply.downloadProgress.disconnect(self._slotNetworkProgress)
except:
pass
self.reply.downloadProgress.connect(self._slotNetworkProgress)
@decorators.BetaImplementation
def put(self, data, location):
self.request.setUrl(QtCore.QUrl("%s%s" % (self.url, localtion)))
self.reply = self.manager.put(data, self.request)
try:
self.reply.uploadProgress.disconnect(self._slotNetworkProgress)
self.reply.downloadProgress.disconnect(self._slotNetworkProgress)
except:
pass
self.uploadProgress.connect(self.slotNetworkProgress)
@decorators.BetaImplementation
def copy(self, fromLocation, toLocation):
self.request.setUrl("%s%s" % (self.url, fromLocaltion))
data = self.manager.get(self.request)
self.put(data.readAll(), toLocation)
@QtCore.pyqtSlot()
def _slotNetworkStart(self):
self.start.emit()
@QtCore.pyqtSlot()
def _slotNetworkFinished(self, reply=None):
self.finished.emit()
#@QtCore.pyqtSlot(QtCore.QByteArray)
# def _slotNetWorkData(self, b):
# buffer = b
# self.data.emit(b)
def _slotNetworkProgress(self, bDone, bTotal):
self.dataTransferProgress.emit(bDone, bTotal)
data_ = None
reply_ = self.reply.readAll().data()
try:
data_ = str(reply_, encoding="iso-8859-15")
except:
data_ = str(reply_, encoding="utf-8")
self.data.emit(data_)
示例12: PDFWidget
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import get [as 别名]
class PDFWidget(QLabel):
'''
A widget showing one page of a PDF.
If you want to show multiple pages of the same PDF,
make sure you share the document (let the first PDFWidget
create the document, then pass thatPDFwidget.document to any
subsequent widgets you create) or use a ScrolledPDFWidget.
'''
def __init__(self, url, document=None, pageno=1, dpi=72, parent=None,
load_cb=None):
'''
load_cb: will be called when the document is loaded.
'''
super(PDFWidget, self).__init__(parent)
self.filename = url
self.load_cb = load_cb
self.network_manager = None
self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
if not document:
self.document = None
if url:
self.start_load(url)
else:
self.document = document
self.page = None
self.pagesize = QSize(600, 800)
self.dpi = dpi
# Poppler page numbering starts from 0 but that's not what
# most PDF users will expect, so subtract:
if pageno > 0:
pageno -= 1
self.pageno = pageno
self.render()
def sizeHint(self):
if not self.page:
if not self.document:
return QSize(600, 800)
self.page = self.document.page(self.pageno)
if not self.pagesize:
self.pagesize = self.page.pageSize()
return self.pagesize
def render(self):
'''Render to a pixmap at the current DPI setting.
'''
if not self.document:
return
if not self.page:
self.page = self.document.page(self.pageno)
self.pagesize = self.page.pageSize()
self.document.setRenderHint(Poppler.Document.TextAntialiasing)
# self.document.setRenderHint(Poppler.Document.TextHinting)
# Most Qt5 programs seem to use setGeometry(x, y, w, h)
# to set initial window size. resize() is the only method I've
# found that doesn't force initial position as well as size.
# self.resize(self.pagesize.width() * self.dpi/POINTS_PER_INCH,
# self.pagesize.height() * self.dpi/POINTS_PER_INCH)
self.setWindowTitle('PDF Viewer')
img = self.page.renderToImage(self.dpi, self.dpi)
self.pixmap = QPixmap.fromImage(img)
self.setPixmap(self.pixmap)
def start_load(self, url):
'''Create a Poppler.Document from the given URL, QUrl or filename.
Return, then asynchronously call self.load_cb.
'''
# If it's not a local file, we'll need to load it.
# http://doc.qt.io/qt-5/qnetworkaccessmanager.html
qurl = QUrl(url)
if not qurl.scheme():
qurl = QUrl.fromLocalFile(url)
if not self.network_manager:
self.network_manager = QNetworkAccessManager();
self.network_manager.finished.connect(self.download_finished)
self.network_manager.get(QNetworkRequest(qurl))
def download_finished(self, network_reply):
qbytes = network_reply.readAll()
self.document = Poppler.Document.loadFromData(qbytes)
self.render()
#.........这里部分代码省略.........
示例13: MostWatchedItems
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import get [as 别名]
class MostWatchedItems(QWidget):
def __init__(self, parent=None):
super(MostWatchedItems, self).__init__(parent)
self.ui = Ui_MostWatchedItems()
self.ui.setupUi(self)
self.ui.tableWidget.setColumnCount(5)
self.ui.tableWidget.setColumnWidth(0, 160)
self.ui.tableWidget.setColumnWidth(1, 480)
self.categoryID = ''
self.manager = QNetworkAccessManager(self)
diskCache = QNetworkDiskCache(self)
diskCache.setCacheDirectory("cache")
self.manager.setCache(diskCache)
self.manager.finished.connect(self.on_finished)
self.manager.sslErrors.connect(self.on_sslErrors)
self.replyMap = dict()
@pyqtSlot(bool)
def on_selectPushButton_clicked(self, checked):
dialog = CategoryInfoDialog.instance()
res = dialog.exec()
if res == QDialog.Accepted:
self.ui.categoryLineEdit.setText('%s -> %s' % (dialog.categoryID(), dialog.categoryNamePath()))
self.categoryID = dialog.categoryID()
@pyqtSlot(bool)
def on_clearPushButton_clicked(self, checked):
self.ui.categoryLineEdit.setText('')
self.categoryID = ''
@pyqtSlot(bool)
def on_wipePushButton_clicked(self, checked):
while self.ui.tableWidget.rowCount() > 0:
self.ui.tableWidget.removeRow(0)
@pyqtSlot(bool)
def on_searchPushButton_clicked(self, checked):
if self.categoryID != '' and self.categoryID != '-1':
merchandising = Merchandising(warnings = False)
response = merchandising.execute(
'getMostWatchedItems',
{
'categoryId': self.categoryID,
'maxResults': self.ui.spinBox.value()
}
)
reply = response.reply
itemRecommendations = reply.itemRecommendations.item
row = self.ui.tableWidget.rowCount()
for item in itemRecommendations:
self.ui.tableWidget.insertRow(row)
imageUrl = 'http://thumbs3.ebaystatic.com/pict/%s4040.jpg' % item.itemId
request = QNetworkRequest(QUrl(imageUrl))
request.setAttribute(QNetworkRequest.CacheLoadControlAttribute, QNetworkRequest.PreferCache)
reply = self.manager.get(request)
self.replyMap[reply] = row
viewItemURL = QLabel()
viewItemURL.setOpenExternalLinks(True)
#viewItemURL.setTextInteractionFlags(Qt.TextBrowserInteraction)
title = '<a href="%s">%s</a>' % (item.viewItemURL, item.title)
viewItemURL.setText(title)
self.ui.tableWidget.setCellWidget(row, 1, viewItemURL)
self.ui.tableWidget.setItem(row, 2, QTableWidgetItem(item.primaryCategoryName))
self.ui.tableWidget.setItem(row, 3, QTableWidgetItem(item.buyItNowPrice.value))
self.ui.tableWidget.setItem(row, 4, QTableWidgetItem(item.watchCount))
row += 1
@pyqtSlot(QNetworkReply)
def on_finished(self, reply):
if reply in self.replyMap:
row = self.replyMap.get(reply)
del self.replyMap[reply]
pixmap = QPixmap()
pixmap.loadFromData(reply.readAll())
image = QLabel()
image.setPixmap(pixmap)
self.ui.tableWidget.setCellWidget(row, 0, image)
self.ui.tableWidget.setRowHeight(row, 160)
@pyqtSlot(QNetworkReply, list)
def on_sslErrors(self, reply, errors):
if reply in self.replyMap:
del self.replyMap[reply]
示例14: OctoPrintOutputDevice
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import get [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):
#.........这里部分代码省略.........
示例15: PluginManager
# 需要导入模块: from PyQt5.QtNetwork import QNetworkAccessManager [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkAccessManager import get [as 别名]
class PluginManager(QObject):
"""
Class implementing the Plugin Manager.
@signal shutdown() emitted at shutdown of the IDE
@signal pluginAboutToBeActivated(modulName, pluginObject) emitted just
before a plugin is activated
@signal pluginActivated(moduleName, pluginObject) emitted just after
a plugin was activated
@signal allPlugginsActivated() emitted at startup after all plugins have
been activated
@signal pluginAboutToBeDeactivated(moduleName, pluginObject) emitted just
before a plugin is deactivated
@signal pluginDeactivated(moduleName, pluginObject) emitted just after
a plugin was deactivated
"""
shutdown = pyqtSignal()
pluginAboutToBeActivated = pyqtSignal(str, object)
pluginActivated = pyqtSignal(str, object)
allPlugginsActivated = pyqtSignal()
pluginAboutToBeDeactivated = pyqtSignal(str, object)
pluginDeactivated = pyqtSignal(str, object)
def __init__(self, parent=None, doLoadPlugins=True, develPlugin=None):
"""
Constructor
The Plugin Manager deals with three different plugin directories.
The first is the one, that is part of eric6 (eric6/Plugins). The
second one is the global plugin directory called 'eric6plugins',
which is located inside the site-packages directory. The last one
is the user plugin directory located inside the .eric6 directory
of the users home directory.
@param parent reference to the parent object (QObject)
@keyparam doLoadPlugins flag indicating, that plugins should
be loaded (boolean)
@keyparam develPlugin filename of a plugin to be loaded for
development (string)
@exception PluginPathError raised to indicate an invalid plug-in path
"""
super(PluginManager, self).__init__(parent)
self.__ui = parent
self.__develPluginFile = develPlugin
self.__develPluginName = None
self.__inactivePluginsKey = "PluginManager/InactivePlugins"
self.pluginDirs = {
"eric6": os.path.join(getConfig('ericDir'), "Plugins"),
"global": os.path.join(Utilities.getPythonModulesDirectory(),
"eric6plugins"),
"user": os.path.join(Utilities.getConfigDir(), "eric6plugins"),
}
self.__priorityOrder = ["eric6", "global", "user"]
self.__defaultDownloadDir = os.path.join(
Utilities.getConfigDir(), "Downloads")
self.__activePlugins = {}
self.__inactivePlugins = {}
self.__onDemandActivePlugins = {}
self.__onDemandInactivePlugins = {}
self.__activeModules = {}
self.__inactiveModules = {}
self.__onDemandActiveModules = {}
self.__onDemandInactiveModules = {}
self.__failedModules = {}
self.__foundCoreModules = []
self.__foundGlobalModules = []
self.__foundUserModules = []
self.__modulesCount = 0
pdirsExist, msg = self.__pluginDirectoriesExist()
if not pdirsExist:
raise PluginPathError(msg)
if doLoadPlugins:
if not self.__pluginModulesExist():
raise PluginModulesError
self.__insertPluginsPaths()
self.__loadPlugins()
self.__checkPluginsDownloadDirectory()
self.pluginRepositoryFile = \
os.path.join(Utilities.getConfigDir(), "PluginRepository")
# attributes for the network objects
self.__networkManager = QNetworkAccessManager(self)
self.__networkManager.proxyAuthenticationRequired.connect(
proxyAuthenticationRequired)
if SSL_AVAILABLE:
self.__sslErrorHandler = E5SslErrorHandler(self)
self.__networkManager.sslErrors.connect(self.__sslErrors)
#.........这里部分代码省略.........