예제 #1
0
파일: __init__.py 프로젝트: ollawone/stdm
def setup_logger():
    from stdm.settings.registryconfig import debug_logging

    logger = logging.getLogger('stdm')
    logger.setLevel(logging.ERROR)

    # Create log directory if it does not exist
    log_folder = QDir()
    if not log_folder.exists(LOG_DIR):
        status = log_folder.mkpath(LOG_DIR)

        # Log directory could not be created
        if not status:
            raise IOError('Log directory for STDM could not be created.')

    # File handler for logging debug messages
    file_handler = TimedRotatingFileHandler(LOG_FILE_PATH, when='D',
                                            interval=1, backupCount=14)
    file_handler.setLevel(logging.DEBUG)

    # Create formatter and add it to the handler
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler.setFormatter(formatter)

    # Add handler to the logger
    logger.addHandler(file_handler)

    # Enable/disable debugging. Defaults to ERROR level.
    lvl = debug_logging()
    if lvl:
        file_handler.setLevel(logging.DEBUG)
    else:
        file_handler.setLevel(logging.ERROR)
예제 #2
0
    def uploadDocument(self, entity_source, doc_type, fileinfo):
        """
        Upload document in central repository
        """
        self._entity_source = entity_source
        self._doc_type = doc_type
        self.fileID = self.generateFileID()
        self.sourcePath = str(fileinfo.filePath())
        profile_name = self.curr_profile.name
        root_dir = QDir(self.networkPath)
        doc_dir = QDir('{}/{}/{}/{}'.format(
            self.networkPath, profile_name.lower(), self._entity_source,
            self._doc_type.lower().replace(' ', '_')))
        doc_path_str = '{}/{}/{}/{}'.format(
            self.networkPath, profile_name.lower(), self._entity_source,
            self._doc_type.lower().replace(' ', '_')).lower()

        if not doc_dir.exists():
            res = root_dir.mkpath(doc_path_str)
            if res:
                root_doc_type_path = doc_path_str

            else:
                root_doc_type_path = self.networkPath

        else:
            root_doc_type_path = doc_path_str

        self.destinationPath = '{}/{}.{}'.format(root_doc_type_path,
                                                 self.fileID,
                                                 fileinfo.completeSuffix())

        srcFile = open(self.sourcePath, 'rb')
        destinationFile = open(self.destinationPath, 'wb')

        # srcLen = self.sourceFile.bytesAvailable()
        totalRead = 0
        while True:
            inbytes = srcFile.read(4096)
            if not inbytes:
                break
            destinationFile.write(inbytes)
            totalRead += len(inbytes)
            # Raise signal on each block written
            self.blockWritten.emit(totalRead)

        self.completed.emit(self.fileID)

        srcFile.close()
        destinationFile.close()

        return self.fileID
예제 #3
0
    def accept(self):
        project_name = self.project_name_le.text()
        if project_name.endswith('.qgs'):
            project_name = project_name[:-4]
        if not project_name:
            QMessageBox.critical(self, self.tr("OQ-Consolidate: Error"),
                                 self.tr("Please specify the project name"))
            return

        outputDir = self.leOutputDir.text()
        if not outputDir:
            QMessageBox.critical(
                self, self.tr("OQ-Consolidate: Error"),
                self.tr("Please specify the output directory."))
            return
        outputDir = os.path.join(outputDir, get_valid_filename(project_name))

        # create main directory if not exists
        d = QDir(outputDir)
        if not d.exists():
            if not d.mkpath("."):
                QMessageBox.critical(
                    self, self.tr("OQ-Consolidate: Error"),
                    self.tr("Can't create directory to store the project."))
                return

        # create directory for layers if not exists
        if d.exists("layers"):
            res = QMessageBox.question(
                self, self.tr("Directory exists"),
                self.tr("Output directory already contains 'layers'"
                        " subdirectory. Maybe this directory was used to"
                        " consolidate another project. Continue?"),
                QMessageBox.Yes | QMessageBox.No)
            if res == QMessageBox.No:
                return
        else:
            if not d.mkdir("layers"):
                QMessageBox.critical(
                    self, self.tr("OQ-Consolidate: Error"),
                    self.tr("Can't create directory for layers."))
                return

        # copy project file
        projectFile = QgsProject.instance().fileName()
        if projectFile:
            f = QFile(projectFile)
            newProjectFile = os.path.join(outputDir, '%s.qgs' % project_name)
            f.copy(newProjectFile)
        else:
            newProjectFile = os.path.join(outputDir, '%s.qgs' % project_name)
            f = QFileInfo(newProjectFile)
            p = QgsProject.instance()
            p.write(f)

        # start consolidate thread that does all real work
        self.workThread = consolidatethread.ConsolidateThread(
            self.iface, outputDir, newProjectFile,
            self.checkBoxZip.isChecked())
        self.workThread.rangeChanged.connect(self.setProgressRange)
        self.workThread.updateProgress.connect(self.updateProgress)
        self.workThread.processFinished.connect(self.processFinished)
        self.workThread.processInterrupted.connect(self.processInterrupted)
        self.workThread.processError.connect(self.processError)
        self.workThread.exceptionOccurred.connect(self.exceptionOccurred)

        self.btnClose.setText(self.tr("Cancel"))
        self.btnOk.setEnabled(False)
        self.buttonBox.rejected.disconnect(self.reject)
        self.btnClose.clicked.connect(self.stopProcessing)

        self.workThread.start()
예제 #4
0
    def accept(self):
        self.btnOk.setEnabled(False)
        self.btnCancel.setEnabled(False)
        project_name = self.project_name_le.text()
        if project_name.endswith('.qgs'):
            project_name = project_name[:-4]
        if not project_name:
            msg = tr("Please specify the project name")
            log_msg(msg, level='C', message_bar=iface.messageBar())
            self.restoreGui()
            return

        outputDir = self.leOutputDir.text()
        if not outputDir:
            msg = tr("Please specify the output directory.")
            log_msg(msg, level='C', message_bar=iface.messageBar())
            self.restoreGui()
            return
        outputDir = os.path.join(outputDir, get_valid_filename(project_name))

        # create main directory if not exists
        d = QDir(outputDir)
        if not d.exists():
            if not d.mkpath("."):
                msg = tr("Can't create directory to store the project.")
                log_msg(msg, level='C', message_bar=iface.messageBar())
                self.restoreGui()
                return

        # create directory for layers if not exists
        if d.exists("layers"):
            res = QMessageBox.question(
                self, self.tr("Directory exists"),
                self.tr("Output directory already contains 'layers'"
                        " subdirectory. Maybe this directory was used to"
                        " consolidate another project. Continue?"),
                QMessageBox.Yes | QMessageBox.No)
            if res == QMessageBox.No:
                self.restoreGui()
                return
        else:
            if not d.mkdir("layers"):
                msg = tr("Can't create directory for layers.")
                log_msg(msg, level='C', message_bar=iface.messageBar())
                self.restoreGui()
                return

        # copy project file
        projectFile = QgsProject.instance().fileName()
        try:
            if projectFile:
                f = QFile(projectFile)
                newProjectFile = os.path.join(outputDir,
                                              '%s.qgs' % project_name)
                f.copy(newProjectFile)
            else:
                newProjectFile = os.path.join(outputDir,
                                              '%s.qgs' % project_name)
                p = QgsProject.instance()
                p.write(newProjectFile)
        except Exception as exc:
            self.restoreGui()
            log_msg(str(exc),
                    level='C',
                    message_bar=iface.messageBar(),
                    exception=exc)
            return

        # start consolidate task that does all real work
        self.consolidateTask = ConsolidateTask('Consolidation',
                                               QgsTask.CanCancel, outputDir,
                                               newProjectFile,
                                               self.checkBoxZip.isChecked(),
                                               self.cb.currentText())
        self.consolidateTask.begun.connect(self.on_consolidation_begun)

        QgsApplication.taskManager().addTask(self.consolidateTask)
        super().accept()