def exportTextFile(self, fh=None, header=None, data=None): """Writes data to the given file. Accepts column names and the data as arguments """ if not fh: self.mkError("Could not open file for writing") return if not data: data = [] if not len(data): self.mkWarn("No data to write") return fname = QFile(fh) if fname.open(QFile.WriteOnly | QFile.Text): txt = QTextStream(fname) if header: txt << ", ".join(col for col in header) txt << "\n" txt << "\n".join(", ".join(item) for item in data) msg = "File export complete: {0}".format(str(fname.fileName())) self.mkSuccess(msg)
def parse_knitting_symbol(symbolPath): """ Parse the knitting symbol located at path symbolPath. """ descriptionFile = QFile(symbolPath + "/description") if (not descriptionFile.exists()) or descriptionFile.error(): return None # parse XML dom = QDomDocument() (status, msg, line, col) = dom.setContent(descriptionFile) if not status: errorMessage = ("Failed reading pattern description in file %s -- " "%s at line %d column %d" % (descriptionFile.fileName(), msg, line, col)) logger.error(errorMessage) return None # make sure we're reading a sconcho pattern description root = dom.documentElement() if root.tagName() != "sconcho": return None # parse the actual content node = root.firstChild() if node.toElement().tagName() != "knittingSymbol": return None content = parse_symbol_description(node) # add the absolute path content["svgPath"] = symbolPath + "/" + content["svgName"] + ".svg" return content
def run(self): self.mutex.lock() self.stopMe = 0 self.mutex.unlock() interrupted = False outPath = self.outDir if outPath.find("\\") != -1: outPath.replace("\\", "/") if not outPath.endswith("/"): outPath = outPath + "/" provider = self.layer.dataProvider() index = provider.fieldNameIndex(self.field) unique = ftools_utils.getUniqueValues(provider, int(index)) baseName = unicode(outPath + self.layer.name() + "_" + self.field + "_") fieldList = ftools_utils.getFieldList(self.layer) sRs = provider.crs() geom = self.layer.wkbType() inFeat = QgsFeature() self.emit(SIGNAL("rangeCalculated(PyQt_PyObject)"), len(unique)) for i in unique: check = QFile(baseName + "_" + unicode(i).strip() + ".shp") fName = check.fileName() if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(fName): self.errors.append(fName) continue writer = QgsVectorFileWriter(fName, self.encoding, fieldList, geom, sRs) fit = provider.getFeatures() while fit.nextFeature(inFeat): atMap = inFeat.attributes() if atMap[index] == i: writer.addFeature(inFeat) del writer self.emit(SIGNAL("valueProcessed()")) self.mutex.lock() s = self.stopMe self.mutex.unlock() if s == 1: interrupted = True break if not interrupted: self.emit(SIGNAL("processFinished( PyQt_PyObject )"), self.errors) else: self.emit(SIGNAL("processInterrupted()"))
def run(self): self.mutex.lock() self.stopMe = 0 self.mutex.unlock() interrupted = False outPath = self.outDir if outPath.find("\\") != -1: outPath.replace("\\", "/") if not outPath.endswith("/"): outPath = outPath + "/" provider = self.layer.dataProvider() index = provider.fieldNameIndex(self.field) unique = ftools_utils.getUniqueValues(provider, int(index)) baseName = unicode( outPath + self.layer.name() + "_" + self.field + "_" ) fieldList = ftools_utils.getFieldList(self.layer) sRs = provider.crs() geom = self.layer.wkbType() inFeat = QgsFeature() self.emit(SIGNAL("rangeCalculated(PyQt_PyObject)"), len(unique)) for i in unique: check = QFile(baseName + "_" + unicode(i).strip() + ".shp") fName = check.fileName() if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(fName): self.errors.append( fName ) continue writer = QgsVectorFileWriter(fName, self.encoding, fieldList, geom, sRs) fit = provider.getFeatures() while fit.nextFeature(inFeat): atMap = inFeat.attributes() if atMap[index] == i: writer.addFeature(inFeat) del writer self.emit(SIGNAL("valueProcessed()")) self.mutex.lock() s = self.stopMe self.mutex.unlock() if s == 1: interrupted = True break if not interrupted: self.emit(SIGNAL("processFinished( PyQt_PyObject )"), self.errors) else: self.emit(SIGNAL("processInterrupted()"))
def exportDatabase(self): """Export entire traces database in CSV format.""" con, cur = dbms.connect(DB) # get column names - sqlite only cur.execute("PRAGMA table_info(traces)") cols = cur.fetchall() header = ", ".join([str(col[1]) for col in cols]) data = [] for row in cur.execute("select * from traces"): data.append(", ".join(str(item) for item in row)) con.close() if not len(data): self.statusBar().showMessage("No data to write", 3000) return export_path = os.path.join(BNDB_PATH, "Export") if not os.path.exists(export_path): os.mkdir(export_path) fh = QFileDialog.getSaveFileName(self, "Export Database", export_path, "Text files (*.txt);;All Files (*.*)") if not fh: self.statusBar().showMessage("Cancelled database export.", 3000) return if QFileInfo(fh).suffix().isEmpty(): fh += ".txt" fname = QFile(fh) if fname.open(QFile.WriteOnly | QFile.Text): txt = QTextStream(fname) txt << "{0}\n".format(header) # IGNORE:W0106 txt << "\n".join(item for item in data) # IGNORE:W0106 self.statusBar().showMessage("Database export complete", 5000) QMessageBox.information(self, "Information", ("Database exported to: " "<p><font color='blue'>{0}</blue>" "</p>".format(str(fname.fileName()))))
def load_stylesheet(pyside=True): """ Loads the stylesheet. Takes care of importing the rc module. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string """ # Smart import of the rc file if pyside: import qdarkstyle.pyside_style_rc else: import qdarkstyle.pyqt_style_rc # Load the stylesheet content from resources if not pyside: from PyQt4.QtCore import QFile, QTextStream else: from PySide.QtCore import QFile, QTextStream f = QFile("qdarkstyle/style.qss") if not f.exists(): _logger().error("Unable to load stylesheet, file not found in " "resources") return "" else: print(f.fileName()) f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() if platform.system().lower() == 'darwin': # see issue #12 on github mac_fix = ''' QDockWidget::title { background-color: #353434; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
def readThemeIndex(self, themeName): dirList = [] parents = [] themeIndex = QFile() # Read theme index files for i in range(len(self.iconDirs)): themeIndex.setFileName(path.join(unicode(self.iconDirs[i]), unicode(themeName), "index.theme")) if themeIndex.exists(): indexReader = QSettings(themeIndex.fileName(), QSettings.IniFormat) for key in indexReader.allKeys(): if key.endsWith("/Size"): size = indexReader.value(key).toInt() dirList.append((size[0], unicode(key.left(key.size() - 5)))) parents = indexReader.value('Icon Theme/Inherits') parents = parents.toStringList() break return QIconTheme(dirList, parents)
class ResourceReply(QNetworkReply): def __init__(self, filePath, parent): super(ResourceReply, self).__init__(parent) self.source = QFile(filePath, self) QTimer.singleShot(0, self._SH_finish) def __del__(self): print "ResourceReply deleted", self.source.fileName() def isSequential(self): return True def open(self, mode): self.source.open(mode) return super(ResourceReply, self).open(mode) def close(self): self.source.close() super(ResourceReply, self).close() def bytesAvailable(self): return self.source.bytesAvailable() + super(ResourceReply, self).bytesAvailable() def readData(self, maxSize): return self.source.read(maxSize) def abort(self): self.source.close() def _SH_finish(self): self.setHeader(QNetworkRequest.ContentLengthHeader, self.source.bytesAvailable()) self.open(QNetworkReply.ReadOnly) self.finished.emit()
class ResourceReply(QNetworkReply): def __init__(self, filePath, parent): super(ResourceReply, self).__init__(parent) self.source = QFile(filePath, self) QTimer.singleShot(0, self._SH_finish); def __del__(self): print "ResourceReply deleted", self.source.fileName() def isSequential(self): return True def open(self, mode): self.source.open(mode) return super(ResourceReply, self).open(mode) def close(self): self.source.close(); super(ResourceReply, self).close() def bytesAvailable(self): return self.source.bytesAvailable() + super(ResourceReply, self).bytesAvailable() def readData(self, maxSize): return self.source.read(maxSize) def abort(self): self.source.close() def _SH_finish(self): self.setHeader(QNetworkRequest.ContentLengthHeader, self.source.bytesAvailable()) self.open(QNetworkReply.ReadOnly) self.finished.emit()
def readThemeIndex(self, themeName): dirList = [] parents = [] themeIndex = QFile() # Read theme index files for i in range(len(self.iconDirs)): themeIndex.setFileName( path.join(unicode(self.iconDirs[i]), unicode(themeName), "index.theme")) if themeIndex.exists(): indexReader = QSettings(themeIndex.fileName(), QSettings.IniFormat) for key in indexReader.allKeys(): if key.endsWith("/Size"): size = indexReader.value(key).toInt() dirList.append( (size[0], unicode(key.left(key.size() - 5)))) parents = indexReader.value('Icon Theme/Inherits') parents = parents.toStringList() break return QIconTheme(dirList, parents)
class InstanceUUIDExtractor(): """ Class constructor """ def __init__(self, path): """ Initatlize class variables """ self.file_path = path self.file = None self.new_list = [] self.doc = QDomDocument() self.node = QDomNode() def set_file_path(self, path): """ Update the path based on the new file being read :param path: :return: """ self.file_path = path def unset_path(self): """Clear the current document path""" self.file_path = None def set_document(self): """ :return: """ self.file = QFile(self.file_path) if self.file.open(QIODevice.ReadOnly): self.doc.setContent(self.file) self.file.close() def update_document(self): '''Update the current instance by clearing the document in the cache ''' self.doc.clear() self.set_document() def on_file_passed(self): """ Pass the raw file to an xml document object and format the its filename to GeoODK standards :return: """ try: self.set_document() self.read_uuid_element() self.doc.clear() self.file.close() self.rename_file() except: pass def read_uuid_element(self): """ get the uuid element and text from the xml document from the mobile divice """ node = self.doc.elementsByTagName("meta") for i in range(node.count()): node = node.item(i).firstChild().toElement() self.node = node.text() return self.node def document_entities(self, profile): """ Get entities in the document :return: """ self.set_document() node_list = [] nodes = self.doc.elementsByTagName(profile) node = nodes.item(0).childNodes() if node: for j in range(node.count()): node_val = node.item(j) node_list.append(node_val.nodeName()) return node_list def profile_entity_nodes(self, profile): ''' Fetch and return QDomNodeList for entities of a profile :rtype: QDomNodeList ''' self.set_document() nodes = self.doc.elementsByTagName(profile) return nodes.item(0).childNodes() def document_entities_with_data(self, profile, selected_entities): """ Get entities in the dom document matching user selected entities :rtype: OrderedDict """ instance_data = OrderedDict() self.set_document() nodes = self.doc.elementsByTagName(profile) entity_nodes = nodes.item(0).childNodes() for attrs in range(entity_nodes.count()): if entity_nodes.item(attrs).nodeName() in selected_entities: name_entity = entity_nodes.item(attrs).nodeName() attr_nodes = self.doc.elementsByTagName(name_entity) instance_data[attr_nodes] = name_entity return instance_data def attribute_data_from_nodelist(self, args_list): """ process nodelist data before Importing attribute data into db """ repeat_instance_data = OrderedDict() attribute_data = OrderedDict() for attr_nodes, entity in args_list.iteritems(): '''The assuption is that there are repeated entities from mobile sub forms. handle them separately''' if attr_nodes.count() > 1: for i in range(attr_nodes.count()): attrib_node = attr_nodes.at(i).childNodes() attr_list = OrderedDict() for j in range(attrib_node.count()): field_name = attrib_node.at(j).nodeName() field_value = attrib_node.at(j).toElement().text() attr_list[field_name] = field_value repeat_instance_data['{}'.format(i) + entity] = attr_list else: '''Entities must appear onces in the form''' node_list_var = OrderedDict() attr_node = attr_nodes.at(0).childNodes() for j in range(attr_node.count()): field_name = attr_node.at(j).nodeName() field_value = attr_node.at(j).toElement().text() node_list_var[field_name] = field_value attribute_data[entity] = node_list_var return attribute_data, repeat_instance_data def read_attribute_data_from_node(self, node, entity_name): """Read attribute data from a node item""" node_list_var = OrderedDict() attributes = OrderedDict() attr_node = node.at(0).childNodes() for j in range(attr_node.count()): field_name = attr_node.at(j).nodeName() field_value = attr_node.at(j).toElement().text() node_list_var[field_name] = field_value attributes[entity_name] = node_list_var return attributes def str_definition(self, instance=None): """ Check if the instance file has entry social tenure :return: """ if instance: self.set_file_path(instance) self.set_document() attributes = {} nodes = self.doc.elementsByTagName('social_tenure') entity_nodes = nodes.item(0).childNodes() if entity_nodes: for j in range(entity_nodes.count()): node_val = entity_nodes.item(j).toElement() attributes[node_val.nodeName()] = node_val.text().rstrip() return attributes def has_str_captured_in_instance(self, instance): """ Bool if the str inclusion is required based on whether is captured or not :return: """ count = len(self.str_definition(instance)) return True if count > 1 else False def entity_atrributes(self): """ Get collected data from the entity in the document :return: """ pass def uuid_element(self): """ Format the guuid from the file :return: """ return self.node.replace(":", "") def rename_file(self): """ Remane the existing instance file with Guuid from the mobile divice to conform with GeoODk naming convention :return: """ if isinstance(self.file, QFile): dir_n, file_n = os.path.split(self.file_path) os.chdir(dir_n) if not file_n.startswith(UUID): new_file_name = self.uuid_element() + ".xml" isrenamed = self.file.setFileName(new_file_name) os.rename(file_n, new_file_name) self.new_list.append(new_file_name) return isrenamed else: self.new_list.append(self.file.fileName()) self.file.close() else: return def file_list(self): """ check through the list of document to ensure they are complete file path """ complete_file = [] for fi in self.new_list: if os.path.isfile(fi): complete_file.append(fi) else: continue return complete_file def close_document(self): '''Close all the open documents and unset current paths''' self.file_path = None self.doc.clear() self.new_list = None
class InstanceUUIDExtractor(): """ Class constructor """ def __init__(self, path): """ Initatlize class variables """ self.file_path = path self.file = None self.new_list = [] self.doc = QDomDocument() self.node = QDomNode() def set_file_path(self, path): """ Update the path based on the new file being read :param path: :return: """ self.file_path = path def set_document(self): """ :return: """ self.file = QFile(self.file_path) if self.file.open(QIODevice.ReadOnly): self.doc.setContent(self.file) def on_file_passed(self): """ Pass the row file to an xml document and format the name to GeoODK standards :return: """ try: self.set_document() self.read_uuid_element() self.doc.clear() self.file.close() self.rename_file() except: pass def read_uuid_element(self): """ get the uuid element and text from the xml document from the mobile divice """ node = self.doc.elementsByTagName("meta") for i in range(node.count()): node = node.item(i).firstChild().toElement() self.node = node.text() return self.node def document_entities(self, profile): """ Get entities in the document :return: """ self.set_document() node_list = [] nodes = self.doc.elementsByTagName(profile) node = nodes.item(0).childNodes() if node: for j in range(node.count()): node_val = node.item(j) node_list.append(node_val.nodeName()) return node_list def str_definition(self): """ Check if the instance file has entry social tenure :return: """ attributes = {} nodes = self.doc.elementsByTagName('social_tenure') entity_nodes = nodes.item(0).childNodes() if entity_nodes: for j in range(entity_nodes.count()): node_val = entity_nodes.item(j).toElement() attributes[node_val.nodeName()] = node_val.text().rstrip() return attributes def has_str_captured_in_instance(self): """ Bool if the str inclusion is required based on whether is captured or not :return: """ str_defined = False count = len(self.str_definition()) if count > 1: str_defined = True else: str_defined = False return str_defined def entity_atrributes(self): """ Get collected data from the entity in the document :return: """ pass def uuid_element(self): """ Format the guuid from the file :return: """ return self.node.replace(":", "") def rename_file(self): """ Remane the existing instance file with Guuid from the mobile divice to conform with GeoODk naming convention :return: """ if isinstance(self.file, QFile): dir_n, file_n = os.path.split(self.file_path) os.chdir(dir_n) if not file_n.startswith(UUID): new_file_name = self.uuid_element() + ".xml" isrenamed = self.file.setFileName(new_file_name) os.rename(file_n, new_file_name) self.new_list.append(new_file_name) return isrenamed else: self.new_list.append(self.file.fileName()) #print str(self.new_list) else: return
class QgsPluginInstallerInstallingDialog( QDialog, Ui_QgsPluginInstallerInstallingDialogBase): # ----------------------------------------- # def __init__(self, parent, plugin): QDialog.__init__(self, parent) self.setupUi(self) self.plugin = plugin self.mResult = "" self.progressBar.setRange(0, 0) self.progressBar.setFormat("%p%") self.labelName.setText(plugin["name"]) self.buttonBox.clicked.connect(self.abort) url = QUrl(plugin["download_url"]) fileName = plugin["filename"] tmpDir = QDir.tempPath() tmpPath = QDir.cleanPath(tmpDir + "/" + fileName) self.file = QFile(tmpPath) self.request = QNetworkRequest(url) self.reply = QgsNetworkAccessManager.instance().get(self.request) self.reply.downloadProgress.connect(self.readProgress) self.reply.finished.connect(self.requestFinished) self.stateChanged(4) # ----------------------------------------- # def result(self): return self.mResult # ----------------------------------------- # def stateChanged(self, state): messages = [ self.tr("Installing..."), self.tr("Resolving host name..."), self.tr("Connecting..."), self.tr("Host connected. Sending request..."), self.tr("Downloading data..."), self.tr("Idle"), self.tr("Closing connection..."), self.tr("Error") ] self.labelState.setText(messages[state]) # ----------------------------------------- # def readProgress(self, done, total): if total > 0: self.progressBar.setMaximum(total) self.progressBar.setValue(done) # ----------------------------------------- # def requestFinished(self): reply = self.sender() self.buttonBox.setEnabled(False) if reply.error() != QNetworkReply.NoError: self.mResult = reply.errorString() if reply.error() == QNetworkReply.OperationCanceledError: self.mResult += "<br/><br/>" + QCoreApplication.translate( "QgsPluginInstaller", "If you haven't cancelled the download manually, it might be caused by a timeout. In this case consider increasing the connection timeout value in QGIS options." ) self.reject() reply.deleteLater() return self.file.open(QFile.WriteOnly) self.file.write(reply.readAll()) self.file.close() self.stateChanged(0) reply.deleteLater() pluginDir = qgis.utils.home_plugin_path tmpPath = self.file.fileName() # make sure that the parent directory exists if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) # if the target directory already exists as a link, remove the link without resolving: QFile(pluginDir + unicode(QDir.separator()) + self.plugin["id"]).remove() try: unzip( unicode(tmpPath), unicode(pluginDir) ) # test extract. If fails, then exception will be raised and no removing occurs # removing old plugin files if exist removeDir(QDir.cleanPath( pluginDir + "/" + self.plugin["id"])) # remove old plugin if exists unzip(unicode(tmpPath), unicode(pluginDir)) # final extract. except: self.mResult = self.tr( "Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:" ) + "\n" + pluginDir self.reject() return try: # cleaning: removing the temporary zip file QFile(tmpPath).remove() except: pass self.close() # ----------------------------------------- # def abort(self): if self.reply.isRunning(): self.reply.finished.disconnect() self.reply.abort() del self.reply self.mResult = self.tr("Aborted by user") self.reject()
class QgsPluginInstallerInstallingDialog(QDialog, Ui_QgsPluginInstallerInstallingDialogBase): # ----------------------------------------- # def __init__(self, parent, plugin): QDialog.__init__(self, parent) self.setupUi(self) self.plugin = plugin self.mResult = "" self.progressBar.setRange(0,0) self.progressBar.setFormat("%p%") self.labelName.setText(plugin["name"]) self.buttonBox.clicked.connect(self.abort) url = QUrl(plugin["download_url"]) fileName = plugin["filename"] tmpDir = QDir.tempPath() tmpPath = QDir.cleanPath(tmpDir+"/"+fileName) self.file = QFile(tmpPath) self.request = QNetworkRequest(url) self.reply = QgsNetworkAccessManager.instance().get( self.request ) self.reply.downloadProgress.connect( self.readProgress ) self.reply.finished.connect(self.requestFinished) self.stateChanged(4) # ----------------------------------------- # def result(self): return self.mResult # ----------------------------------------- # def stateChanged(self, state): messages=[self.tr("Installing..."),self.tr("Resolving host name..."),self.tr("Connecting..."),self.tr("Host connected. Sending request..."),self.tr("Downloading data..."),self.tr("Idle"),self.tr("Closing connection..."),self.tr("Error")] self.labelState.setText(messages[state]) # ----------------------------------------- # def readProgress(self, done, total): if total > 0: self.progressBar.setMaximum(total) self.progressBar.setValue(done) # ----------------------------------------- # def requestFinished(self): reply = self.sender() self.buttonBox.setEnabled(False) if reply.error() != QNetworkReply.NoError: self.mResult = reply.errorString() if reply.error() == QNetworkReply.OperationCanceledError: self.mResult += "<br/><br/>" + QCoreApplication.translate("QgsPluginInstaller", "If you haven't cancelled the download manually, it might be caused by a timeout. In this case consider increasing the connection timeout value in QGIS options.") self.reject() reply.deleteLater() return self.file.open(QFile.WriteOnly) self.file.write(reply.readAll()) self.file.close() self.stateChanged(0) reply.deleteLater() pluginDir = qgis.utils.home_plugin_path tmpPath = self.file.fileName() # make sure that the parent directory exists if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) # if the target directory already exists as a link, remove the link without resolving: QFile(pluginDir+unicode(QDir.separator())+self.plugin["id"]).remove() try: unzip(unicode(tmpPath), unicode(pluginDir)) # test extract. If fails, then exception will be raised and no removing occurs # removing old plugin files if exist removeDir(QDir.cleanPath(pluginDir+"/"+self.plugin["id"])) # remove old plugin if exists unzip(unicode(tmpPath), unicode(pluginDir)) # final extract. except: self.mResult = self.tr("Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:") + "\n" + pluginDir self.reject() return try: # cleaning: removing the temporary zip file QFile(tmpPath).remove() except: pass self.close() # ----------------------------------------- # def abort(self): if self.reply.isRunning(): self.reply.finished.disconnect() self.reply.abort() del self.reply self.mResult = self.tr("Aborted by user") self.reject()
class Saver(QDialog): '''Classe qui permet d'enregistrer un fichier sur le disque''' def __init__(self, login, password, url, nameFile, parent = None): ''' Constructeur @type login: String @param login: Compte utilisateur @type password: String @param password: Mot de passe utilisateur @type url:String @param url: URL de la ressource @type nameFile: String @param nameFile: Nom du fichier ''' super(Saver, self).__init__(parent) self.url_to_download = url self.login = login self.password = password self.nameFile = nameFile #Création des parametres self.parameters = parse_qs(urlparse(url).query) self.httpGetId = 0 self.requeteHTTPannule = False self.statusLabel = QLabel(u'Enregistrement %s' % self.url_to_download) self.closeButton = QPushButton("Fermer") self.closeButton.setAutoDefault(False) self.openFileButton = QPushButton("Ouvrir le fichier") self.openFileButton.setAutoDefault(False) self.openDirectoryButton = QPushButton(u"Ouvrir le répertoire") self.openDirectoryButton.setAutoDefault(False) self.progressBar = QProgressBar() #Gestion des boutons inférieurs buttonBox = QDialogButtonBox() buttonBox.addButton(self.openFileButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.openDirectoryButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole) #Construction de l'objet QHTTP et mise en place des signaux/slots self.http = QHttp(self) self.http.requestFinished.connect(self.httpRequestFinished) self.http.dataReadProgress.connect(self.updateDataReadProgress) self.http.responseHeaderReceived.connect(self.readResponseHeader) self.closeButton.clicked.connect(self.cancelDownload) self.openDirectoryButton.clicked.connect(self.openDirectory) self.openFileButton.clicked.connect(self.openFile) #Construction de l'interface mainLayout = QVBoxLayout() mainLayout.addWidget(self.statusLabel) mainLayout.addWidget(self.progressBar) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) #Création de la fenêtre et affichage self.setWindowTitle(u'Enregistrement') self.openFileButton.hide() self.openDirectoryButton.hide() self.show() #Lancement du téléchargement self.downloadFile() def downloadFile(self): url = QUrl(self.url_to_download) fileName = QFileDialog.getSaveFileName(self, "Enregistrer la liste des dossiers", self.nameFile, "conf") if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information(self, 'Erreur','Impossible d\'enregistrer le fichier %s: %s.' % (fileName, self.outFile.errorString())) self.outFile = None return #Création que la connexion HTTPS mode = QHttp.ConnectionModeHttps port = 0 self.http.setHost(url.host(), mode, port) self.requeteHTTPannule = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' #Concaténation des paramètres à l'URL path = path+("?") for item in url.queryItems(): path = path + item[0] + "=" + item[1] + "&" self.http.setUser(self.login, self.password) self.httpGetId = self.http.get(path, self.outFile) def cancelDownload(self): self.statusLabel.setText(u"Enregistrement annulé") self.requeteHTTPannule = True self.http.abort() self.close() def httpRequestFinished(self, requestId, error): if requestId != self.httpGetId: return if self.requeteHTTPannule: if self.outFile is not None: self.outFile.close() self.outFile.remove() self.outFile = None return self.outFile.close() self.progressBar.setMinimum(0) self.progressBar.setMaximum(100) self.progressBar.setValue(100) if error: self.outFile.remove() QMessageBox.information(self, 'Erreur','Le téléchargement a échoué : %s.' % self.http.errorString()) self.statusLabel.setText('Enregistrement ok') self.openDirectoryButton.show() self.openFileButton.show() def readResponseHeader(self, responseHeader): '''Slot pour analyser les headers HTTP''' if responseHeader.statusCode() not in (200, 300, 301, 302, 303, 307): QMessageBox.information(self, 'Erreur','Le téléchargement a échoué : %s.' % responseHeader.reasonPhrase()) self.requeteHTTPannule = True self.http.abort() def updateDataReadProgress(self, bytesRead, totalBytes): '''Slot pour mettre à jour la barre de progression''' if self.requeteHTTPannule: return self.progressBar.setMaximum(totalBytes) self.progressBar.setValue(bytesRead) def openFile(self): '''Fonction permettant d'ouvrir le fichier''' desktopService = QDesktopServices() desktopService.openUrl(QUrl(self.outFile.fileName())) def openDirectory(self): '''Fonction permettant d'ouvrir le répertoire''' desktopService = QDesktopServices() fileInfo = QFileInfo(QFile(self.outFile.fileName())) directory = fileInfo.dir() desktopService.openUrl(QUrl(directory.path()))