def proxy_from_url(url: QUrl) -> Union[QNetworkProxy, pac.PACFetcher]: """Create a QNetworkProxy from QUrl and a proxy type. Args: url: URL of a proxy (possibly with credentials). Return: New QNetworkProxy. """ ensure_valid(url) scheme = url.scheme() if scheme in ['pac+http', 'pac+https', 'pac+file']: fetcher = pac.PACFetcher(url) fetcher.fetch() return fetcher types = { 'http': QNetworkProxy.HttpProxy, 'socks': QNetworkProxy.Socks5Proxy, 'socks5': QNetworkProxy.Socks5Proxy, 'direct': QNetworkProxy.NoProxy, } if scheme not in types: raise InvalidProxyTypeError(scheme) proxy = QNetworkProxy(types[scheme], url.host()) if url.port() != -1: proxy.setPort(url.port()) if url.userName(): proxy.setUser(url.userName()) if url.password(): proxy.setPassword(url.password()) return proxy
def __init__(self, remoteName, remoteUrl, parent=None): """ Constructor @param remoteName name of the remote repository @type str @param remoteUrl URL of the remote repository @type str @param parent reference to the parent widget @type QWidget """ super(GitRemoteCredentialsDialog, self).__init__(parent) self.setupUi(self) url = QUrl(remoteUrl) self.nameEdit.setText(remoteName) self.urlEdit.setText(url.toString(QUrl.RemoveUserInfo)) self.userEdit.setText(url.userName()) self.passwordEdit.setText(url.password()) self.userEdit.setFocus(Qt.OtherFocusReason) msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height())
def transform(self, value): if not value: return None elif value == 'system': return SYSTEM_PROXY elif value == 'none': return QNetworkProxy(QNetworkProxy.NoProxy) url = QUrl(value) typ = self.PROXY_TYPES[url.scheme()] proxy = QNetworkProxy(typ, url.host()) if url.port() != -1: proxy.setPort(url.port()) if url.userName(): proxy.setUser(url.userName()) if url.password(): proxy.setPassword(url.password()) return proxy
def __init__(self, parent): """ Copies the properties from the parent (WebEngineRenderer) object, creates the required instances of QWebPage, QWebView and QMainWindow and registers some Slots. """ QObject.__init__(self) # Copy properties from parent for key, value in parent.__dict__.items(): setattr(self, key, value) # Determine Proxy settings proxy = QNetworkProxy(QNetworkProxy.NoProxy) if 'http_proxy' in os.environ: proxy_url = QUrl(os.environ['http_proxy']) if proxy_url.scheme().startswith('http'): protocol = QNetworkProxy.HttpProxy else: protocol = QNetworkProxy.Socks5Proxy proxy = QNetworkProxy(protocol, proxy_url.host(), proxy_url.port(), proxy_url.userName(), proxy_url.password()) # Create and connect required PyQt5 objects self._page = CustomWebPage(logger=self.logger, ignore_alert=self.ignoreAlert, ignore_confirm=self.ignoreConfirm, ignore_prompt=self.ignorePrompt, interrupt_js=self.interruptJavaScript) self._qt_proxy = QNetworkProxy() self._qt_proxy.setApplicationProxy(proxy) self._view = QWebEngineView() self._view.setPage(self._page) _window_flags = Qt.WindowFlags() self._window = QMainWindow(flags=_window_flags) self._window.setCentralWidget(self._view) self._qt_network_access_manager = QNetworkAccessManager() # Import QWebSettings for key, value in self.qWebSettings.items(): self._page.settings().setAttribute(key, value) # Connect required event listeners # assert False, "Not finish" self._page.loadFinished.connect(self._on_load_finished) self._page.loadStarted.connect(self._on_load_started) self._qt_network_access_manager.sslErrors.connect(self._on_ssl_errors) self._qt_network_access_manager.finished.connect(self._on_each_reply) # The way we will use this, it seems to be unnecessary to have Scrollbars enabled self._scroll_area = QAbstractScrollArea() self._scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self._scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # Show this widget self._window.show()
def __init__(self, connections=None, parent=None): """ Constructor @param connections list of database connections to add (list of strings) @param parent reference to the parent widget (QWidget) """ super(SqlBrowser, self).__init__(parent) self.setObjectName("SqlBrowser") if connections is None: connections = [] self.setWindowTitle(self.tr("SQL Browser")) self.setWindowIcon(UI.PixmapCache.getIcon("eric.png")) self.setStyle(Preferences.getUI("Style"), Preferences.getUI("StyleSheet")) from .SqlBrowserWidget import SqlBrowserWidget self.__browser = SqlBrowserWidget(self) self.setCentralWidget(self.__browser) self.__browser.statusMessage.connect(self.statusBar().showMessage) self.__initActions() self.__initMenus() self.__initToolbars() self.resize(self.__browser.size()) self.__warnings = [] for connection in connections: url = QUrl(connection, QUrl.TolerantMode) if not url.isValid(): self.__warnings.append( self.tr("Invalid URL: {0}").format(connection)) continue err = self.__browser.addConnection(url.scheme(), url.path(), url.userName(), url.password(), url.host(), url.port(-1)) if err.type() != QSqlError.NoError: self.__warnings.append( self.tr("Unable to open connection: {0}".format( err.text()))) QTimer.singleShot(0, self.__uiStartUp)
def __init__(self, connections=[], parent=None): """ Constructor @param connections list of database connections to add (list of strings) @param parent reference to the parent widget (QWidget) """ super(SqlBrowser, self).__init__(parent) self.setObjectName("SqlBrowser") self.setWindowTitle(self.tr("SQL Browser")) self.setWindowIcon(UI.PixmapCache.getIcon("eric.png")) self.setStyle(Preferences.getUI("Style"), Preferences.getUI("StyleSheet")) from .SqlBrowserWidget import SqlBrowserWidget self.__browser = SqlBrowserWidget(self) self.setCentralWidget(self.__browser) self.__browser.statusMessage.connect(self.statusBar().showMessage) self.__initActions() self.__initMenus() self.__initToolbars() self.resize(self.__browser.size()) self.__warnings = [] for connection in connections: url = QUrl(connection, QUrl.TolerantMode) if not url.isValid(): self.__warnings.append( self.tr("Invalid URL: {0}").format(connection)) continue err = self.__browser.addConnection(url.scheme(), url.path(), url.userName(), url.password(), url.host(), url.port(-1)) if err.type() != QSqlError.NoError: self.__warnings.append( self.tr("Unable to open connection: {0}".format( err.text()))) QTimer.singleShot(0, self.__uiStartUp)
class HttpWindow(QMainWindow): def __init__(self, parent=None): super(HttpWindow, self).__init__(parent) self.title = "OraDocs by littleT" self.left = 10 self.top = 10 self.width = 600 self.height = 400 self.docRoot = "https://oradocs-corp.documents.us2.oraclecloud.com/documents/" self.url = QUrl() self.qnam = QNetworkAccessManager() self.reply = None self.outFile = None self.httpGetId = 0 self.httpRequestAborted = False self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.statusBar().showMessage('Starting ...') # for the menu first create some actions to be added like # File - Exit action exitAction = QAction(QIcon('exit24.png'), 'Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit Application') exitAction.triggered.connect(self.close) # File - open openAction = QAction(QIcon(''), '&Open', self) openAction.setShortcut('Ctrl+O') openAction.setStatusTip('Opens a file') openAction.triggered.connect(self.openCall) # the help actions helpAction = QAction(QIcon(''), 'Help', self) helpAction.triggered.connect(self.openHelp) mainMenu = self.menuBar() fileMenu = mainMenu.addMenu('&File') fileMenu.addAction(openAction) fileMenu.addAction(exitAction) helpMenu = mainMenu.addMenu('&Help') helpMenu.addAction(helpAction) self.urlLineEdit = QLineEdit(self) self.urlLineEdit.setGeometry(5, 250, 590, 20) self.urlLineEdit.setText(self.docRoot) self.downloadButton = QPushButton('Click Me', self) self.downloadButton.move(10, 275) self.downloadButton.clicked.connect(self.onDownloadClick) self.quitButton = QPushButton("Quit", self) self.quitButton.setAutoDefault(False) self.quitButton.clicked.connect(self.close) self.quitButton.move(120, 275) self.logOutput = QTextEdit(self) self.logOutput.setReadOnly(True) # self.logOutput.setLineWrapMode(QTextEdit.NoWrap) self.logOutput.setGeometry(5, 320, 590, 60) self.logOutput.setSizePolicy(self.sizePolicy) self.statusBar().showMessage('waiting for click ...') def openCall(self): QMessageBox.information(self, "Info", "File Open Menu, work in progress") def openHelp(self): QMessageBox.information(self, "Info", "Help Menu, work in progress") def onDownloadClick(self): self.url = QUrl(self.docRoot) self.logOutput.insertPlainText("onclick before startReq -> url %s\n" % self.url.toString()) # start the request self.startRequest(self.url) self.logOutput.insertPlainText("onclick after startReq -> url %s\n" % self.url.toString()) # do we need authorization self.qnam.authenticationRequired.connect( self.slotAuthenticationRequired) # do we go ssl errors self.qnam.sslErrors.connect(self.sslErrors) def httpFinished(self): self.logOutput.insertPlainText("httpFinished ...\n") self.logOutput.moveCursor(QTextCursor.End) if self.httpRequestAborted: # if self.outFile is not None: # self.outFile.close() # self.outFile.remove() # self.outFile = None self.logOutput.insertPlainText("httpFinished, httpReqAbr ...\n") self.logOutput.moveCursor(QTextCursor.End) self.reply.deleteLater() # self.outFile.flush() # self.outFile.close() return # maybe updating progress or so # self.progressDialog.hide() # self.outFile.flush() # self.outFile.close() # check for redirection redirectionTarget = self.reply.attribute( QNetworkRequest.RedirectionTargetAttribute) if self.reply.error(): # are we got an error # self.outFile.remove() QMessageBox.information(self, "HTTP", "Download failed %s" % self.reply.errorString) elif redirectionTarget is not None: # self.logOutput.insertPlainText("httpFinished, redirect from %s\n" # % str(self.url)) self.logOutput.moveCursor(QTextCursor.End) # do we got redirected newUrl = self.url.resolved(redirectionTarget) self.logOutput.insertPlainText("httpFinished, redirect \n") # % newUrl.toString()) self.logOutput.moveCursor(QTextCursor.End) #ret = QMessageBox.question(self, "HTTP", "Redirect to %s." % # newUrl.toString(), # QMessageBox.Yes | QMessageBox.No) #if ret == QMessageBox.Yes: # # if we saied yes to redirect set the new URL to redirected one # self.url = newUrl # # the reply needs to be nothing # self.reply = None # # self.outFile.open(QIODevice.WriteOnly) # # self.outFile.resize(0) # # and start over # self.startRequest(self.url) # return # the new url is the redirected one self.url = newUrl # the reply needs to be nothing self.reply = None # and start over self.startRequest(self.url) return else: # fileName = QFileInfo(QUrl(self.urlLineEdit.text()).path()).fileName() # self.statusLabel.setText("Downloaded %s to %s." % (fileName, QDir.currentPath())) # self.statusLabel.setText("Done") self.statusBar().showMessage("Done") self.reply.deleteLater() self.reply = None # self.outFile = None def startRequest(self, url): self.logOutput.insertPlainText("startRequest ...\n") self.logOutput.moveCursor(QTextCursor.End) # get the requested page self.reply = self.qnam.get(QNetworkRequest(url)) # if we are finished self.reply.finished.connect(self.httpFinished) # are we ready to read the stuff # self.reply.readyRead.connect(self.httpReadyRead) # downloading # self.reply.downloadProgress.connect(self.updateDataReadProgress) def slotAuthenticationRequired(self, authenticator): import os from PyQt5 import uic self.logOutput.insertPlainText("Authentication ...\n") self.logOutput.moveCursor(QTextCursor.End) self.logOutput.moveCursor(QTextCursor.End) self.logOutput.insertPlainText(str(authenticator)) ui = os.path.join(os.path.dirname(__file__), 'authenticationdialog.ui') self.logOutput.moveCursor(QTextCursor.End) self.logOutput.insertPlainText(str(ui)) dlg = uic.loadUi(ui) dlg.adjustSize() dlg.siteDescription.setText("%s at %s" % (authenticator.realm(), self.url.host())) dlg.userEdit.setText(self.url.userName()) dlg.passwordEdit.setText(self.url.password()) if dlg.exec_() == QDialog.Accepted: authenticator.setUser(dlg.userEdit.text()) authenticator.setPassword(dlg.passwordEdit.text()) def sslErrors(self, reply, errors): errorString = ", ".join([str(error.errorString()) for error in errors]) ret = QMessageBox.warning(self, "HTTP Example", "One or more SSL errors has occurred: %s" % errorString, QMessageBox.Ignore | QMessageBox.Abort) if ret == QMessageBox.Ignore: self.reply.ignoreSslErrors()
def queryProxy(self, query): """ Public method to determine a proxy for a given query. @param query reference to the query object (QNetworkProxyQuery) @return list of proxies in order of preference (list of QNetworkProxy) """ if query.queryType() == QNetworkProxyQuery.UrlRequest and \ query.protocolTag() in ["http", "https", "ftp"]: # use proxy at all ? if not Preferences.getUI("UseProxy"): return [QNetworkProxy(QNetworkProxy.NoProxy)] # test for exceptions exceptions = Preferences.getUI("ProxyExceptions") if exceptions != self.__exceptions: self.__setExceptions(exceptions) urlHost = query.url().host() for matcher in self.__hostnameMatchers: if matcher.match(urlHost): return [QNetworkProxy(QNetworkProxy.NoProxy)] # determine proxy if Preferences.getUI("UseSystemProxy"): proxyList = QNetworkProxyFactory.systemProxyForQuery(query) if not Globals.isWindowsPlatform() and \ len(proxyList) == 1 and \ proxyList[0].type() == QNetworkProxy.NoProxy: # try it the Python way # scan the environment for variables named <scheme>_proxy # scan over whole environment to make this case insensitive for name, value in os.environ.items(): name = name.lower() if value and name[-6:] == '_proxy' and \ name[:-6] == query.protocolTag().lower(): url = QUrl(value) if url.scheme() == "http": proxyType = QNetworkProxy.HttpProxy elif url.scheme() == "https": proxyType = QNetworkProxy.HttpCachingProxy elif url.scheme() == "ftp": proxyType = QNetworkProxy.FtpCachingProxy else: proxyType = QNetworkProxy.HttpProxy proxy = QNetworkProxy(proxyType, url.host(), url.port(), url.userName(), url.password()) proxyList = [proxy] break if proxyList: scheme = schemeFromProxyType(proxyList[0].type()) if scheme == "": scheme = "Http" if scheme != "NoProxy": proxyList[0].setUser( Preferences.getUI("ProxyUser/{0}".format(scheme))) proxyList[0].setPassword( Preferences.getUI( "ProxyPassword/{0}".format(scheme))) return proxyList else: return [QNetworkProxy(QNetworkProxy.NoProxy)] else: if Preferences.getUI("UseHttpProxyForAll"): protocolKey = "Http" else: protocolKey = query.protocolTag().capitalize() host = Preferences.getUI("ProxyHost/{0}".format(protocolKey)) if not host: E5MessageBox.critical( None, QCoreApplication.translate( "E5NetworkProxyFactory", "Proxy Configuration Error"), QCoreApplication.translate( "E5NetworkProxyFactory", """Proxy usage was activated""" """ but no proxy host for protocol""" """ '{0}' configured.""").format(protocolKey)) return [QNetworkProxy(QNetworkProxy.DefaultProxy)] else: if protocolKey in ["Http", "Https", "Ftp"]: if query.protocolTag() == "ftp": proxyType = QNetworkProxy.FtpCachingProxy elif query.protocolTag() == "https": proxyType = QNetworkProxy.HttpCachingProxy else: proxyType = QNetworkProxy.HttpProxy proxy = QNetworkProxy( proxyType, host, Preferences.getUI("ProxyPort/" + protocolKey), Preferences.getUI("ProxyUser/" + protocolKey), Preferences.getUI("ProxyPassword/" + protocolKey)) else: proxy = QNetworkProxy(QNetworkProxy.DefaultProxy) return [proxy, QNetworkProxy(QNetworkProxy.DefaultProxy)] else: return [QNetworkProxy(QNetworkProxy.NoProxy)]
def queryProxy(self, query): """ Public method to determine a proxy for a given query. @param query reference to the query object (QNetworkProxyQuery) @return list of proxies in order of preference (list of QNetworkProxy) """ if query.queryType() == QNetworkProxyQuery.UrlRequest and query.protocolTag() in ["http", "https", "ftp"]: # use proxy at all ? if not Preferences.getUI("UseProxy"): return [QNetworkProxy(QNetworkProxy.NoProxy)] # test for exceptions exceptions = Preferences.getUI("ProxyExceptions") if exceptions != self.__exceptions: self.__setExceptions(exceptions) urlHost = query.url().host() for matcher in self.__hostnameMatchers: if matcher.match(urlHost): return [QNetworkProxy(QNetworkProxy.NoProxy)] # determine proxy if Preferences.getUI("UseSystemProxy"): proxyList = QNetworkProxyFactory.systemProxyForQuery(query) if ( not Globals.isWindowsPlatform() and len(proxyList) == 1 and proxyList[0].type() == QNetworkProxy.NoProxy ): # try it the Python way # scan the environment for variables named <scheme>_proxy # scan over whole environment to make this case insensitive for name, value in os.environ.items(): name = name.lower() if value and name[-6:] == "_proxy" and name[:-6] == query.protocolTag().lower(): url = QUrl(value) if url.scheme() == "http": proxyType = QNetworkProxy.HttpProxy elif url.scheme() == "https": proxyType = QNetworkProxy.HttpCachingProxy elif url.scheme() == "ftp": proxyType = QNetworkProxy.FtpCachingProxy else: proxyType = QNetworkProxy.HttpProxy proxy = QNetworkProxy(proxyType, url.host(), url.port(), url.userName(), url.password()) proxyList = [proxy] break if proxyList: scheme = schemeFromProxyType(proxyList[0].type()) if scheme == "": scheme = "Http" if scheme != "NoProxy": proxyList[0].setUser(Preferences.getUI("ProxyUser/{0}".format(scheme))) proxyList[0].setPassword(Preferences.getUI("ProxyPassword/{0}".format(scheme))) return proxyList else: return [QNetworkProxy(QNetworkProxy.NoProxy)] else: if Preferences.getUI("UseHttpProxyForAll"): protocolKey = "Http" else: protocolKey = query.protocolTag().capitalize() host = Preferences.getUI("ProxyHost/{0}".format(protocolKey)) if not host: E5MessageBox.critical( None, QCoreApplication.translate("E5NetworkProxyFactory", "Proxy Configuration Error"), QCoreApplication.translate( "E5NetworkProxyFactory", """Proxy usage was activated""" """ but no proxy host for protocol""" """ '{0}' configured.""", ).format(protocolKey), ) return [QNetworkProxy(QNetworkProxy.DefaultProxy)] else: if protocolKey in ["Http", "Https", "Ftp"]: if query.protocolTag() == "ftp": proxyType = QNetworkProxy.FtpCachingProxy elif query.protocolTag() == "https": proxyType = QNetworkProxy.HttpCachingProxy else: proxyType = QNetworkProxy.HttpProxy proxy = QNetworkProxy( proxyType, host, Preferences.getUI("ProxyPort/" + protocolKey), Preferences.getUI("ProxyUser/" + protocolKey), Preferences.getUI("ProxyPassword/" + protocolKey), ) else: proxy = QNetworkProxy(QNetworkProxy.DefaultProxy) return [proxy, QNetworkProxy(QNetworkProxy.DefaultProxy)] else: return [QNetworkProxy(QNetworkProxy.NoProxy)]
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: self.outFile.close() self.outFile.remove() self.outFile = None self.reply.deleteLater() self.reply = None self.progressDialog.hide() return self.progressDialog.hide() self.outFile.flush() self.outFile.close() redirectionTarget = self.reply.attribute(QNetworkRequest.RedirectionTargetAttribute) if self.reply.error(): self.outFile.remove() QMessageBox.information(self, "HTTP", "Download failed: %s." % self.reply.errorString()) self.downloadButton.setEnabled(True) elif redirectionTarget is not None: newUrl = self.url.resolved(redirectionTarget) ret = QMessageBox.question(self, "HTTP", "Redirect to %s?" % newUrl.toString(), QMessageBox.Yes | QMessageBox.No) if ret == QMessageBox.Yes: self.url = newUrl self.reply.deleteLater() self.reply = None self.outFile.open(QIODevice.WriteOnly) self.outFile.resize(0) self.startRequest(self.url) return else: fileName = QFileInfo(QUrl(self.urlLineEdit.text()).path()).fileName() self.statusLabel.setText("Downloaded %s to %s." % (fileName, QDir.currentPath())) self.downloadButton.setEnabled(True) self.reply.deleteLater() self.reply = None self.outFile = None def httpReadyRead(self): if self.outFile is not None: self.outFile.write(self.reply.readAll()) def updateDataReadProgress(self, bytesRead, totalBytes): if self.httpRequestAborted: return self.progressDialog.setMaximum(totalBytes) self.progressDialog.setValue(bytesRead) def enableDownloadButton(self): self.downloadButton.setEnabled(self.urlLineEdit.text() != '') def slotAuthenticationRequired(self, authenticator): import os from PyQt5 import uic ui = os.path.join(os.path.dirname(__file__), 'authenticationdialog.ui') dlg = uic.loadUi(ui) dlg.adjustSize() dlg.siteDescription.setText("%s at %s" % (authenticator.realm(), self.url.host())) dlg.userEdit.setText(self.url.userName()) dlg.passwordEdit.setText(self.url.password()) if dlg.exec_() == QDialog.Accepted: authenticator.setUser(dlg.userEdit.text()) authenticator.setPassword(dlg.passwordEdit.text()) def sslErrors(self, reply, errors): errorString = ", ".join([str(error.errorString()) for error in errors]) ret = QMessageBox.warning(self, "HTTP Example", "One or more SSL errors has occurred: %s" % errorString, QMessageBox.Ignore | QMessageBox.Abort) if ret == QMessageBox.Ignore: self.reply.ignoreSslErrors()
class AppWindow(QMainWindow): def __init__(self): super().__init__() self.docRoot = "https://oradocs-corp.documents.us2.oraclecloud.com/documents/" self.url = QUrl() self.qnam = QNetworkAccessManager() self.reply = None self.outFile = None self.httpGetId = 0 self.httpRequestAborted = False self.gotToken = False self.ui = Ui_MainWindow() self.ui.setupUi(self) # self.ui.setupUi.MainWindow.setTitle("OraDocs") self._connections() def _connections(self): self.ui.logOutput.insertPlainText( "Setting up actions for all menus and such .") self.ui.action_Exit.triggered.connect(self.close) self.ui.action_Open.triggered.connect(self.action_open) self.ui.action_Save.triggered.connect(self.action_save) self.ui.action_SyncAll.triggered.connect(self.action_syncAll) self.ui.action_SyncConnect.triggered.connect(self.action_syncConnect) self.ui.logOutput.insertPlainText(".. done\n") def startRequest(self, url): # just some debugging to see were we are self.ui.logOutput.insertPlainText("startRequest ...\n") # get the URL self.ui.logOutput.insertPlainText("get page ...\n") self.reply = self.qnam.get(QNetworkRequest(url)) # not sure if here correct or better somwhere else # do we need authorization self.qnam.authenticationRequired.connect( self.slotAuthenticationRequired) # do we got ssl errors self.qnam.sslErrors.connect(self.sslErrors) # after loading the page do some hadling of the output via the pyslot self.reply.finished.connect(self.httpFinished) # we should be able to read the stuff self.ui.logOutput.insertPlainText("before httpReady ...\n") self.reply.readyRead.connect(self.httpReadyRead) # not sure if the return is needed return def httpFinished(self): # just some debugging self.ui.logOutput.insertPlainText("httpFinished start ...\n") # check for redirection redirectionTarget = self.reply.attribute( QNetworkRequest.RedirectionTargetAttribute) # check for reply results if self.reply.error(): # looks like we got an error # self.outFile.remove() QMessageBox.information( self, "HTTP", "Download failed %s" % self.reply.errorString) elif redirectionTarget is not None: # we got redirected # output where we are going to self.ui.logOutput.insertPlainText("redirect -> %s\n" % str(redirectionTarget)) self.ui.logOutput.moveCursor(QTextCursor.End) # our new URL is that one newUrl = self.url.resolved(redirectionTarget) # debug self.ui.logOutput.insertPlainText("new URL -> %s\n" % newUrl.toString()) self.ui.logOutput.moveCursor(QTextCursor.End) # the new url is the redirected one self.url = newUrl # the reply needs to be nothing self.reply = None # and start over self.startRequest(self.url) return else: # do normal processing self.ui.logOutput.insertPlainText("no-redirect -> %s \n" % self.url.toString()) self.ui.logOutput.moveCursor(QTextCursor.End) self.ui.logOutput.insertPlainText( str(self.reply.header(QNetworkRequest.rawHeader))) # as the last actions in here self.reply.deleteLater() self.reply = None def httpReadyRead(self): # if self.outFile is not None: # self.outFile.write(self.reply.readAll()) self.ui.logOutput.insertPlainText("http Ready\n") self.ui.logOutput.moveCursor(QTextCursor.End) myData = self.reply.readAll() # self.ui.logOutput.insertPlainText(str(myData, 'utf-8')) def AuthenticationRequired(self, authenticator): import os from PyQt5 import uic ui = os.path.join(os.path.dirname(__file__), 'authenticationdialog.ui') dlg = uic.loadUi(ui) dlg.adjustSize() dlg.siteDescription.setText("%s at %s" % (authenticator.realm(), self.url.host())) dlg.userEdit.setText(self.url.userName()) dlg.passwordEdit.setText(self.url.password()) if dlg.exec_() == QDialog.Accepted: authenticator.setUser(dlg.userEdit.text()) authenticator.setPassword(dlg.passwordEdit.text()) @pyqtSlot() def action_close(self): # print("closing") self.quit() @pyqtSlot() def action_open(self): # print("open") QMessageBox.information(self, "File Open", "work in progress") @pyqtSlot() def action_save(self): # print("open") QMessageBox.information(self, "File Save", "work in progress") @pyqtSlot() def action_syncAll(self): QMessageBox.information(self, "Sync ALl", "work in progress") @pyqtSlot() # we are starting the the connection actions def action_syncConnect(self): # just some debugging self.ui.logOutput.insertPlainText("syncConnect ...\n") # we start with the root URL self.url = QUrl(self.docRoot) # start the request self.startRequest(self.url) # not sure if here correct or better in httpFinished # do we need authorization self.qnam.authenticationRequired.connect( self.slotAuthenticationRequired) # do we got ssl errors self.qnam.sslErrors.connect(self.sslErrors) # just some debugging self.ui.logOutput.insertPlainText( "syncConnect - after start Request\n") # QMessageBox.information(self, "Sync Connect", "work in progress") @pyqtSlot() def slotAuthenticationRequired(self, authenticator): # import os QMessageBox.information(self, "Authentication", "work in progress") def sslErrors(self, reply, errors): QMessageBox.information(self, "SSL error", "work in progress")
class App(QMainWindow): def __init__(self): super().__init__() self.title = "OraDocs by littleT" self.left = 10 self.top = 10 self.width = 600 self.height = 400 self.initUI() self.url = QUrl() self.qnam = QNetworkAccessManager() self.reply = None self.outFile = None self.httpGetId = 0 self.httpRequestAborted = False def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.statusBar().showMessage('Starting ...') # for the menu first create some actions to be added like # File - Exit action exitAction = QAction(QIcon('exit24.png'), 'Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit Application') exitAction.triggered.connect(self.close) # File - open openAction = QAction(QIcon(''), '&Open', self) openAction.setShortcut('Ctrl+O') openAction.setStatusTip('Opens a file') openAction.triggered.connect(self.openCall()) # the help actions helpAction = QAction(QIcon(''), 'Help', self) helpAction.triggered.connect(self.openHelp) mainMenu = self.menuBar() fileMenu = mainMenu.addMenu('&File') fileMenu.addAction(openAction) fileMenu.addAction(exitAction) helpMenu = mainMenu.addMenu('&Help') helpMenu.addAction(helpAction) self.logOutput = QTextEdit(self) self.logOutput.setReadOnly(True) # self.logOutput.setLineWrapMode(QTextEdit.NoWrap) self.logOutput.setGeometry(5, 200, 590, 60) self.statusBar().showMessage('waiting for click ...') self.urlLineEdit = QLineEdit(self) # self.textbox.move(5, 300) # self.textbox.resize(590, 20) self.urlLineEdit.setGeometry(5, 325, 590, 20) self.button = QPushButton('Click Me', self) self.button.move(10, 350) self.button.clicked.connect(self.doRequest) def doRequest(self): self.root = "https://oradocs-corp.documents.us2.oraclecloud.com/documents/" # url = "https://www.google.com" self.url = QUrl(self.root) self.httpRequestAborted = False self.startRequest(self.url) self.downloadFile() self.qnam.authenticationRequired.connect( self.slotAuthenticationRequired) def startRequest(self, url): self.reply = self.qnam.get(QNetworkRequest(url)) self.reply.finished.connect(self.httpFinished) self.reply.readyRead.connect(self.httpReadyRead) 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: self.outFile.close() self.outFile.remove() self.outFile = None self.reply.deleteLater() self.reply = None # self.progressDialog.hide() return # self.progressDialog.hide() self.outFile.flush() self.outFile.close() redirectionTarget = self.reply.attribute(QNetworkRequest.RedirectionTargetAttribute) if self.reply.error(): self.outFile.remove() QMessageBox.information(self, "HTTP", "Download failed: %s." % self.reply.errorString()) self.downloadButton.setEnabled(True) elif redirectionTarget is not None: newUrl = self.url.resolved(redirectionTarget) ret = QMessageBox.question(self, "HTTP", "Redirect to %s?" % newUrl.toString(), QMessageBox.Yes | QMessageBox.No) if ret == QMessageBox.Yes: self.url = newUrl self.reply.deleteLater() self.reply = None self.outFile.open(QIODevice.WriteOnly) self.outFile.resize(0) self.startRequest(self.url) return else: fileName = QFileInfo(QUrl(self.urlLineEdit.text()).path()).fileName() self.statusLabel.setText("Downloaded %s to %s." % (fileName, QDir.currentPath())) self.downloadButton.setEnabled(True) self.reply.deleteLater() self.reply = None self.outFile = None def httpReadyRead(self): if self.outFile is not None: self.outFile.write(self.reply.readAll()) def updateDataReadProgress(self, bytesRead, totalBytes): if self.httpRequestAborted: return self.progressDialog.setMaximum(totalBytes) self.progressDialog.setValue(bytesRead) def slotAuthenticationRequired(self, authenticator): import os from PyQt5 import uic ui = os.path.join(os.path.dirname(__file__), 'authenticationdialog.ui') dlg = uic.loadUi(ui) dlg.adjustSize() dlg.siteDescription.setText("%s at %s" % (authenticator.realm(), self.url.host())) dlg.userEdit.setText(self.url.userName()) dlg.passwordEdit.setText(self.url.password()) if dlg.exec_() == QDialog.Accepted: authenticator.setUser(dlg.userEdit.text()) authenticator.setPassword(dlg.passwordEdit.text()) def sslErrors(self, reply, errors): errorString = ", ".join([str(error.errorString()) for error in errors]) ret = QMessageBox.warning(self, "HTTP Example", "One or more SSL errors has occurred: %s" % errorString, QMessageBox.Ignore | QMessageBox.Abort) if ret == QMessageBox.Ignore: self.reply.ignoreSslErrors() def openCall(self): print("Open Call") def openHelp(self): print("Open Help") @pyqtSlot() def onClick(self): # textboxValue = self.textbox.text() # QMessageBox.question(self, 'Hello World!', "Confirm: " + textboxValue, # QMessageBox.Ok, QMessageBox.Ok) # self.textbox.setText("...") myRet = self.myDocs.doRequest("https://www.google.com") self.logOutput.moveCursor(QTextCursor.End) print(myRet) self.logOutput.insertPlainText(myRet) @pyqtSlot() def processReq(self): if self.nam.bytesAvailable(): self.logOutput.moveCursor(QTextCursor.End) self.logOutput.insertPlainText('We are connected\n') bytes_string = self.nam.readAll() self.nam.deleteLater() @pyqtSlot(QNetworkReply.NetworkError) def processErr(self, code): self.msg.critical(None, "Info", "You are not connected to the Internet.") print(code)