def read_from_file(uri: str) -> Tuple[QtXml.QDomDocument, str]: """Read a QGIS project (.qgs and .qgz) from a file path and returns d :param uri: path to the file :type uri: str :return: a tuple with XML document and the filepath. :rtype: Tuple[QtXml.QDomDocument, str] """ doc = QtXml.QDomDocument() file = QFile(uri) if (file.exists() and file.open(QIODevice.ReadOnly | QIODevice.Text) and QFileInfo(file).suffix() == "qgs"): doc.setContent(file) project_path = uri elif file.exists() and (QFileInfo(file).suffix() == "qgz"): temporary_unzip = QTemporaryDir() temporary_unzip.setAutoRemove(False) with zipfile.ZipFile(uri, "r") as zip_ref: zip_ref.extractall(temporary_unzip.path()) project_filename = QDir(temporary_unzip.path()).entryList(["*.qgs"])[0] project_path = os.path.join(temporary_unzip.path(), project_filename) xml = QFile(project_path) if xml.open(QIODevice.ReadOnly | QIODevice.Text): doc.setContent(xml) return doc, project_path
def _build_photo_path( self, composition, composer_id, document_parent_table, document_type, doc_id, doc_name ): pic_item = composition.getComposerItemById(composer_id) if pic_item is None: return extensions = doc_name.rsplit(".", 1) if len(extensions) < 2: return network_ph_path = network_document_path() if not network_ph_path: return img_extension = extensions[1] profile_name = self._current_profile.name.replace(' ', '_').lower() abs_path = '{0}/{1}/{2}/{3}/{4}.{5}'.format( network_ph_path, profile_name, document_parent_table, document_type, doc_id, img_extension ) if QFile.exists(abs_path): self._composeritem_value_handler(pic_item, abs_path)
def template_document(self, path): """ Reads the document template file and returns the corresponding QDomDocument. :param path: Absolute path to template file. :type path: str :return: A tuple containing the template document and error message where applicable :rtype: tuple """ if not path: return None, QApplication.translate("DocumentGenerator", "Empty path to document template") if not QFile.exists(path): return None, QApplication.translate("DocumentGenerator", "Path to document template " "does not exist") template_file = QFile(path) if not template_file.open(QIODevice.ReadOnly): return None, QApplication.translate("DocumentGenerator", "Cannot read template file") template_doc = QDomDocument() if template_doc.setContent(template_file): return template_doc, "" return None, QApplication.translate("DocumentGenerator", "Cannot read document template contents")
def clean_up(self): """ Deletes all the tracked SVG files. Usually called when the plugin is being unloaded. """ for sf in self._files: if QFile.exists(sf): QFile.remove(sf)
def readHistoryFile(self): fileExist = QFile.exists(_historyFile) if fileExist: with codecs.open(_historyFile, 'r', encoding='utf-8') as rH: for line in rH: if line != "\n": l = line.rstrip('\n') self.updateHistory(l) else: return
def newItemAddedToLayout(self, item): try: item.setMode(QgsLayoutItemPicture.FormatRaster) except AttributeError: pass item.setFrameEnabled(False) item.setResizeMode(QgsLayoutItemPicture.ZoomResizeFrame) if QFile.exists(self.default_photo): item.setPicturePath(self.default_photo) item.setId(item.uuid())
def __init__(self, uri): DBConnector.__init__(self, uri) self.dbname = uri.database() if not QFile.exists(self.dbname): raise ConnectionError(QApplication.translate("DBManagerPlugin", '"{0}" not found').format(self.dbname)) try: self.connection = spatialite_connect(self._connectionInfo()) except self.connection_error_types() as e: raise ConnectionError(e) self._checkSpatial() self._checkRaster()
def newItemAddedToLayout(self, item): try: item.setMode(QgsLayoutItemPicture.FormatRaster) except AttributeError: pass item.setFrameEnabled(True) item.setFrameStrokeWidth( QgsLayoutMeasurement(0.5, QgsUnitTypes.LayoutMillimeters)) item.setResizeMode(QgsLayoutItemPicture.ZoomResizeFrame) if QFile.exists(self.default_photo): item.setPicturePath(self.default_photo) item.setId(item.uuid())
def objects_from_supporting_doc(self, instance_file=None): """ Create supporting doc path instances based on the collected documents :return:paths :rtype: document object instance """ if instance_file: f_dir, file_name = os.path.split(instance_file) for document, val in self.attributes.items(): if str(document).endswith('supporting_document'): if val != '': doc = self.format_document_name_from_attribute(document) doc_path = os.path.normpath(f_dir + '/' + val) abs_path = doc_path.replace('\\', '/').strip() if QFile.exists(abs_path): self.supporting_document_model(abs_path, doc)
def file_exist(self, doc_model=None, doc_type=None): """ Check if a file exists before removing. """ file_found = True if doc_model is not None: # Build the path from the model variable values. fileName, fileExt = guess_extension(doc_model.filename) profile_name = self.curr_profile.name # Qt always expects the file separator be be "/" regardless of platform. absPath = '{}/{}/{}/{}/{}{}'.format( self.networkPath, profile_name.lower(), doc_model.source_entity, doc_type.lower().replace(' ', '_'), doc_model.document_identifier, fileExt) file_found = QFile.exists(absPath) return file_found
def isValidDatabase(self, path): if not QFile.exists(path): return False try: conn = spatialite_connect(path) except self.connection_error_types(): return False isValid = False try: c = conn.cursor() c.execute("SELECT count(*) FROM sqlite_master") c.fetchone() isValid = True except sqlite.DatabaseError: pass conn.close() return isValid
def test_default_north_arrow_path(self): """Verify the call to default north arrow path works.""" # Check if it exists path = QFile(default_north_arrow_path()) self.assertTrue(QFile.exists(path))
def test_supporters_logo_path(self): """Verify the call to default supporters logo path works.""" # Check if it exists logo_path = QFile(supporters_logo_path()) self.assertTrue(QFile.exists(logo_path))
def test_black_inasafe_logo_path(self): """Verify the call to default InaSAFE logo path works.""" # Check if it exists logo_path = QFile(black_inasafe_logo_path()) self.assertTrue(QFile.exists(logo_path))