Exemple #1
0
 def save(self, outDir, zipName):
     outDir = forceStringEx(outDir)
     try:
         zipFilePath = forceStringEx(
             unicode(os.path.join(outDir, u'%s.zip' % zipName)))
         zf = zipfile.ZipFile(zipFilePath,
                              'w',
                              zipfile.ZIP_DEFLATED,
                              allowZip64=True)
         for reportName in self.documents.keys():
             doc = self.documents[reportName]
             fileName = u''.join([reportName])
             xmlFileName = QtCore.QTemporaryFile(u'%s.xml' % fileName)
             if not xmlFileName.open(QtCore.QFile.WriteOnly):
                 print u'Не удалось открыть временный файл для записи'
                 break
             doc.save(QtCore.QTextStream(xmlFileName), 4,
                      QtXml.QDomNode.EncodingFromDocument)
             xmlFileName.close()
             zf.write(
                 forceStringEx(
                     QtCore.QFileInfo(xmlFileName).absoluteFilePath()),
                 u'%s.xml' % fileName)
             self.documents.pop(reportName)
         zf.close()
     except Exception, e:
         pass
Exemple #2
0
    def __init__(self):
        QtNetwork.QHttp.__init__(self)
        #regionali
        #http://www.televideo.rai.it/televideo/pub/tt4web/Sardegna/page-100.png
        #http://www.televideo.rai.it/televideo/pub/tt4web/Marche/page-100.png
        self.file = QtCore.QTemporaryFile()  #unico file temporaneo
        self.file.setAutoRemove(False)  #lo rimuovo io in chiusura
        self.fileName = QtCore.QString()
        self.httpStatus = 0
        self.ricercaInCorso = False  #è True quando sto cercando pagina successiva a una non trovata
        #queste 2 variabili così se pagina non trovata, posso recuperare quella precedente, in caso utente clicchi No
        self.ultimaPaginaValida = 100
        self.ultimaSottopaginaValida = 1
        self.inAvanti = True  #se sto andando in avanti o indietro, utile per cercare se pagina non trovata nella direzione corretta
        self.downloadInCorso = False  #per disabilitare le azioni

        #settaggio proxy
        npq = QtNetwork.QNetworkProxyQuery(
            QtCore.QUrl("http://www.google.com"))
        listOfProxies = QtNetwork.QNetworkProxyFactory.systemProxyForQuery(npq)
        #print len(listOfProxies)
        if settings.usaProxy == 2:
            self.setProxy(settings.hostProxy, settings.portProxy,
                          settings.userNameProxy, settings.passwordProxy)
        else:
            self.setProxy(listOfProxies[0])

        #segnali, qua perchè se no certe variabili non sono definite
        QtCore.QObject.connect(widget.buttonVai, QtCore.SIGNAL('clicked ()'),
                               self.preparaPagina)
        QtCore.QObject.connect(widget.pagina,
                               QtCore.SIGNAL('valueChanged (int)'),
                               self.preparaPagina)
        QtCore.QObject.connect(widget.sottopagina,
                               QtCore.SIGNAL('valueChanged (int)'),
                               self.caricaSottopagina)
        QtCore.QObject.connect(widget.homeButton, QtCore.SIGNAL('vaiA'),
                               self.preparaPagina)
        QtCore.QObject.connect(widget.customButton1, QtCore.SIGNAL('vaiA'),
                               self.preparaPagina)
        QtCore.QObject.connect(widget.customButton2, QtCore.SIGNAL('vaiA'),
                               self.preparaPagina)
        QtCore.QObject.connect(widget.customButton3, QtCore.SIGNAL('vaiA'),
                               self.preparaPagina)
        QtCore.QObject.connect(widget.customButton4, QtCore.SIGNAL('vaiA'),
                               self.preparaPagina)
        QtCore.QObject.connect(widget.customButton5, QtCore.SIGNAL('vaiA'),
                               self.preparaPagina)
        #QtCore.QObject.connect(widget.indietro,  QtCore.SIGNAL('vaiA'), self.preparaPagina)
        #QtCore.QObject.connect(widget.avanti,  QtCore.SIGNAL('vaiA'), self.preparaPagina)
        QtCore.QObject.connect(widget.saveButton, QtCore.SIGNAL('clicked ()'),
                               self.salvaPagina)
Exemple #3
0
    def loadProgram(self):
        """Stores program into a temporary file and passes its name to analyzer.
        Using a file to communicate with analyzer is for future use like executing without using GUI
        (for automated testing for instance)
        """

        self.clearErrors()
        tmpFile = QtCore.QTemporaryFile()
        tmpFile.open()
        fileData = self.programEdit.toPlainText()
        tmpFile.writeData(fileData)
        tmpFile.close()
        if not self.boardMgr.processFile(tmpFile.fileName()):
            self.displayErrors()
Exemple #4
0
def extractToTempFile(zipFile, fileToExtract):
    """ Распаковывает из архива zipFile(тип ZipFile) файл fileToExtract
        Возвращает QTemporaryFile"""

    outFile = QtCore.QTemporaryFile()

    if not outFile.open(QtCore.QFile.WriteOnly):
        raise CException(u'Экспорт сведений о сотрудниках',
            u'Не могу открыть файл для записи %s:\n%s.' % \
             (outFile, outFile.errorString()))

    data = zipFile.read(fileToExtract)  #read the binary data
    outFile.write(data)
    outFile.close()
    return outFile
Exemple #5
0
    def svg_filepath(self):
        '''
        returns the location of the file holding the users svg data
        if user has  no svg data, a :doc:`GeneratedSvg` is created
        '''
        if self._svg_filepath is None:
            loc = str(QtCore.QDir.tempPath())
            svg_data = self.value("svg_data").toByteArray()
            path = os.path.join(loc, "om_avatar_XXXXXX.svg")
            f = QtCore.QTemporaryFile(path)
            f.setAutoRemove(False)
            if svg_data:
                if f.open(QtCore.QIODevice.WriteOnly):
                    f.writeData(svg_data)
            else:
                if f.open(QtCore.QIODevice.WriteOnly):
                    GeneratedSvg(self.abbrv_name, f.fileName())

            self._svg_filepath = f.fileName()
        return self._svg_filepath
Exemple #6
0
    def save(self, outDir, exportNumber):
        self.phaseReset(2)
        outDir = forceStringEx(outDir)
        self.nextPhase(len(self.documents), u'Сохранение файлов')
        for destArea in self.documents.keys():
            doc, _ = self.documents[destArea]
            insurerFundInfis, currentInfis = self.fileNames[destArea]
            fileName = u''.join([
                u'A',
                self.formatOKATO(insurerFundInfis, 2),
                self.formatOKATO(currentInfis, 2),
                u'%s' % QtCore.QDate.currentDate().toString('yy'),
                u'%.4d' % exportNumber
            ])

            zipFilePath = forceStringEx(
                unicode(os.path.join(outDir, u'%s.oms' % fileName)))
            try:
                xmlFileName = QtCore.QTemporaryFile(u'%s.xml' % fileName)
                if not xmlFileName.open(QtCore.QFile.WriteOnly):
                    self.logger().critical(
                        u'Не удалось открыть временный файл для записи')
                    break
                doc.save(QtCore.QTextStream(xmlFileName), 4,
                         QtXml.QDomNode.EncodingFromDocument)
                xmlFileName.close()
                zf = zipfile.ZipFile(zipFilePath,
                                     'w',
                                     zipfile.ZIP_DEFLATED,
                                     allowZip64=True)
                zf.write(
                    forceStringEx(
                        QtCore.QFileInfo(xmlFileName).absoluteFilePath()),
                    u'%s.xml' % fileName)
                zf.close()
                self.logger().info(u'Создан файл: "%s.oms"' % zipFilePath)
                self.documents.pop(destArea)
            except Exception, e:
                self.logger().critical(u'Не удалось сохранить файл "%s" (%s)' %
                                       (e.message, zipFilePath))
                self.onException()
Exemple #7
0
    def startImport(self):

        self.nProcessed = 0
        self.nPayed = 0
        self.nRefused = 0
        self.nNotFound = 0

        zipFileName = forceStringEx(self.edtFileName.text())

        archive = ZipFile(forceString(zipFileName), "r")
        namelist = archive.namelist()
        if len(namelist) != 2:
            QtGui.QMessageBox.warning(
                self, u'Импорт данных из XML',
                u'Неожиданное количество файлов в архиве.')
            return
        if namelist[0].startswith('H'):
            hFileName, lFileName = namelist
        elif namelist[1].startswith('H'):
            lFileName, hFileName = namelist
        else:
            QtGui.QMessageBox.warning(
                self, u'Импорт данных из XML',
                u'В архиве отсутствует файл с услугами.')
            return
        if not lFileName.startswith('L'):
            QtGui.QMessageBox.warning(
                self, u'Импорт данных из XML',
                u'В архиве отсутствует файл с персональными данными.')
            return

        if len(hFileName) < 8:
            QtGui.QMessageBox.warning(
                self, u'Импорт данных из XML',
                u'Неверный формат имени файла с услугами')
            return

        outFile = QtCore.QTemporaryFile()
        persOutFile = QtCore.QTemporaryFile()

        if not outFile.open(QtCore.QFile.WriteOnly):
            QtGui.QMessageBox.warning(
                self, u'Импорт данных из XML',
                u'Не удаётся открыть временный файл для записи %s:\n%s.' %
                (outFile, outFile.errorString()))
            return
        if not persOutFile.open(QtCore.QFile.WriteOnly):
            QtGui.QMessageBox.warning(
                self, u'Импорт данных из XML',
                u'Не удаётся открыть временный файл для записи %s:\n%s.' %
                (outFile, persOutFile.errorString()))
            return

        self.insurerInfis = hFileName[2:7]

        data = archive.read(hFileName)  #read the binary data
        outFile.write(data)
        outFile.close()
        fileInfo = QtCore.QFileInfo(outFile)

        persData = archive.read(lFileName)
        persOutFile.write(persData)
        persOutFile.close()
        persFileInfo = QtCore.QFileInfo(persOutFile)

        hFile = QtCore.QFile(fileInfo.filePath())
        lFile = QtCore.QFile(persFileInfo.filePath())

        if not hFile.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
            QtGui.QMessageBox.warning(self, u'Импорт данных из XML',
                                  u'Не могу открыть файл для чтения %s:\n%s.' \
                                  % (fileInfo.filePath(), hFile.errorString()))
            return
        if not lFile.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
            QtGui.QMessageBox.warning(self, u'Импорт данных из XML',
                                  u'Не могу открыть файл персональных данных для чтения %s:\n%s.' \
                                  % (persFileInfo.filePath(), lFile.errorString()))
            return

        self.labelNum.setText(u'размер источника: ' +
                              str(hFile.size() + lFile.size()))
        self.progressBar.setFormat('%p%')
        self.progressBar.setMaximum(hFile.size() + lFile.size() - 1)

        self.readLFile(lFile)
        self.readHFile(hFile)

        self.stat.setText(
            u'обработано случаев: %d; оплаченых: %d; отказаных: %d; не найдено: %d' % \
            (self.nProcessed, self.nPayed, self.nRefused, self.nNotFound))
        hFile.close()
        lFile.close()
    def importFormulary(self):
        db = QtGui.qApp.db
        try:
            db.transaction()
            zipFileName = self.edtFileName.text()
            if not is_zipfile(forceString(zipFileName)):
                self.logBrowser.append(u'Файл не является архивом')
                self.logBrowser.update()
                return

            # names = ['Mnn.xlsx', 'Trn.xlsx']
            archive = ZipFile(forceString(zipFileName), "r")
            fileList = archive.namelist()
            for table in self.tables:
                name = self.tables[table]['filename']
                if name not in fileList:
                    self.logBrowser.append(u'В архиве отсутствует файл ' +
                                           name + u'.')
                    self.logBrowser.update()
                    return

            xlsData = {}
            totalEntries = 0
            self.logBrowser.append(
                u'Идет загрузка данных из архива в оперативную память.')
            QtGui.qApp.processEvents()

            for table in self.tables:
                name = self.tables[table]['filename']
                outFile = QtCore.QTemporaryFile()
                if not outFile.open(QtCore.QFile.WriteOnly):
                    self.logBrowser.append(
                        u'Не удаётся открыть файл для записи %s:\n%s.' %
                        (outFile, outFile.errorString()))
                    self.logBrowser.update()
                    return

                data = archive.read(name)
                outFile.write(data)
                outFile.close()
                fileInfo = QtCore.QFileInfo(outFile)

                xlsData[table] = list(
                    CXLSXReader(forceString(fileInfo.filePath())))
                totalEntries += len(xlsData[table]) - 1

            self.logBrowser.append(
                u'Загрузка данных в оперативную память завершена.')
            self.logBrowser.append(
                u'Импорт начат ' +
                QDateTime().currentDateTime().toString('dd.MM.yyyy H:mm:ss') +
                u'.')
            self.progressBar.setMaximum(totalEntries)
            self.progressBar.setFormat('%v/%m')
            QtGui.qApp.processEvents()

            self.nUpdatted = 0
            self.nProcessed = 0
            for table in self.tables:
                items = xlsData[table]
                fields, rows = items[0], items[1:]
                self.processTable(table, fields, rows)

            db.commit()
            self.logBrowser.append(u'--------------------------------------- ')
            self.logBrowser.append(
                u'Импорт завершён ' +
                QDateTime().currentDateTime().toString('dd.MM.yyyy H:mm:ss') +
                u'.')
            self.log.append(
                u'Обработано записей в справочниках: %d; обновлено записей в таблицах: %d'
                % (self.nProcessed, self.nUpdated) + u'.')
            self.logBrowser.append(u'Готово.')
            self.logBrowser.append(u' ')
        except Exception as ex:
            self.log.append(
                u'<b><font color=red>Неизвестная ошибка:</font></b> ' +
                ex.message)
            db.rollback()