Skip to content

Commit

Permalink
Fix add cartodb_id field to updated layers
Browse files Browse the repository at this point in the history
  • Loading branch information
elesdoar committed Sep 1, 2015
1 parent 267a8fb commit 2998433
Show file tree
Hide file tree
Showing 7 changed files with 46 additions and 32 deletions.
13 changes: 8 additions & 5 deletions CartoDBPlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@
# Import the PyQt and QGIS libraries
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *

from qgis.core import QgsMessageLog, QgsPluginLayerRegistry, QgsMapLayerRegistry
from osgeo import gdal
from osgeo import ogr

import resources

from cartodb import CartoDBAPIKey, CartoDBException
from QgisCartoDB.dialogs import CartoDBPluginUpload, CartoDBPluginDialog, CartoDBNewSQLDialog, CartoDBPluginCreateViz
from QgisCartoDB.dialogs.ConnectionManager import CartoDBConnectionsManager
from QgisCartoDB.layers import CartoDBLayer, CartoDBPluginLayer, CartoDBPluginLayerType, CartoDBLayerWorker
Expand All @@ -37,9 +38,11 @@
import os.path
import shutil

from urllib import urlopen

"""
Class CartoDBPlugin
Main plugin class.
"""
class CartoDBPlugin(QObject):
# initialize plugin directory
PLUGIN_DIR = os.path.dirname(os.path.abspath(__file__))
Expand Down Expand Up @@ -236,7 +239,7 @@ def upload(self):
dlg = CartoDBPluginUpload(self.iface, self.toolbar)
def addLayer(fileName, tableName):
newLayer = CartoDBLayer(self.iface, tableName, dlg.currentUser, dlg.currentApiKey,
dlg.currentUser, None, spatiaLite=fileName, multiuser=dlg.currentMultiuser)
dlg.currentUser, None, spatiaLite=fileName, multiuser=dlg.currentMultiuser)
QgsMapLayerRegistry.instance().addMapLayer(newLayer)
self.layers.append(newLayer)

Expand Down
21 changes: 11 additions & 10 deletions dialogs/Upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@
* *
***************************************************************************/
"""
from PyQt4.QtCore import Qt, QSettings, QFile, QFileInfo, QTimer, pyqtSignal, pyqtSlot, qDebug
from PyQt4.QtCore import Qt, QSettings, QFile, QFileInfo, QTimer, QVariant, pyqtSignal, pyqtSlot, qDebug
from PyQt4.QtGui import QApplication, QDialog, QPixmap, QListWidgetItem, QLabel, QSizePolicy

from qgis.core import QgsMapLayerRegistry, QgsMapLayer, QgsVectorFileWriter, QgsField
from qgis.core import QgsMapLayerRegistry, QgsMapLayer, QgsVectorFileWriter, QgsField, QgsVectorLayer
from qgis.gui import QgsMessageBar

from QgisCartoDB.cartodb import CartoDBApi
Expand Down Expand Up @@ -76,11 +76,11 @@ def upload(self):
for layerItem in self.ui.layersList.selectedItems():
widget = self.ui.layersList.itemWidget(layerItem)
qDebug('Layer: ' + str(widget.layer.storageType()))
layer = self.checkCartoDBId(widget.layer)
zipPath = self.zipLayer(layer, self.ui.convertCH.isChecked())
self.uploadZip(zipPath, widget, self.ui.convertCH.isChecked())
layer = self.checkCartoDBId(widget.layer, self.ui.convertCH.isChecked())
zipPath = self.zipLayer(layer)
self.uploadZip(zipPath, widget, layer, self.ui.convertCH.isChecked())

def uploadZip(self, zipPath, widget, convert = False):
def uploadZip(self, zipPath, widget, convertLayer=None, convert=False):
def completeUpload(data):
timer = QTimer(self)

Expand All @@ -101,10 +101,11 @@ def statusComplete(d):
level=QgsMessageBar.INFO, duration=5)

if convert:
self.convert2CartoDB(widget.layer, d['table_name'])
self.convert2CartoDB(convertLayer if convertLayer is not None else widget.layer, d['table_name'])
elif d['state'] == 'failure':
timer.stop()
self.ui.statusLB.setText(QApplication.translate('CartoDBPlugin', '{} failed, {}').format(widget.layer.name(), d['get_error_text']['title']))
self.ui.statusLB.setText(QApplication.translate('CartoDBPlugin', '{} failed, {}').format(
widget.layer.name(), d['get_error_text']['title']))
widget.setStatus(d['state'])
self.ui.bar.clearWidgets()
self.ui.bar.pushMessage(QApplication.translate('CartoDBPlugin', 'Error uploading {}').format(widget.layer.name()),
Expand Down Expand Up @@ -179,7 +180,7 @@ def checkCartoDBId(self, layer, convert = False):
tf = tempfile.NamedTemporaryFile()
error = QgsVectorFileWriter.writeAsVectorFormat(layer, tf.name, 'utf-8', None, 'ESRI Shapefile')
if error == QgsVectorFileWriter.NoError:
ly = QgsVectorLayer(tf.name + '.shp', layer.name() + '-tmp', 'ogr')
ly = QgsVectorLayer(tf.name + '.shp', layer.name(), 'ogr')
res = ly.dataProvider().addAttributes([QgsField('cartodb_id', QVariant.Int)])
ly.updateFields()
features = ly.getFeatures()
Expand Down Expand Up @@ -218,7 +219,7 @@ def zipLayer(self, layer):
if layer.storageType() == 'ESRI Shapefile':
for suffix in ['.shp', '.dbf', '.prj', '.shx']:
if os.path.exists(os.path.join(dirName, fileName + suffix)):
zipFile.write(os.path.join(dirName, fileName + suffix), fileName + suffix, zipfile.ZIP_DEFLATED)
zipFile.write(os.path.join(dirName, fileName + suffix), layer.name() + suffix, zipfile.ZIP_DEFLATED)
elif layer.storageType() == 'GeoJSON':
zipFile.write(filePath, layer.name() + '.geojson', zipfile.ZIP_DEFLATED)
elif layer.storageType() == 'GPX':
Expand Down
8 changes: 6 additions & 2 deletions i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,8 +214,8 @@
<translation>Replace if exists</translation>
</message>
<message>
<source>Add CartoDB layer to project</source>
<translation>Add CartoDB layer to project</translation>
<source>Add CartoDB layer to project (this could truncate the column's names)</source>
<translation>Add CartoDB layer to project (this could truncate the column's names)</translation>
</message>
<message>
<source>Cancel</source>
Expand All @@ -225,6 +225,10 @@
<source>Upload</source>
<translation>Upload</translation>
</message>
<message>
<source>Ready</source>
<translation>Listo</translation>
</message>
</context>
<context>
<name>CreateViz</name>
Expand Down
8 changes: 6 additions & 2 deletions i18n/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,8 +214,8 @@
<translation>Reemplazar si existe en CartoDB</translation>
</message>
<message>
<source>Add CartoDB layer to project</source>
<translation>Agregar capa CartoDB al proyecto</translation>
<source>Add CartoDB layer to project (this could truncate the column's names)</source>
<translation>Agregar capa CartoDB al proyecto (esto podría truncar los nombres de las columnas)</translation>
</message>
<message>
<source>Cancel</source>
Expand All @@ -225,6 +225,10 @@
<source>Upload</source>
<translation>Subir</translation>
</message>
<message>
<source>Ready</source>
<translation>Listo</translation>
</message>
</context>
<context>
<name>CreateViz</name>
Expand Down
23 changes: 11 additions & 12 deletions layers/CartoDBLayer.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,10 @@

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *

from osgeo import gdal
from qgis.core import QgsFeatureRequest, QgsVectorLayer, QgsMessageLog, QgsDataSourceURI
from osgeo import ogr

import os.path

from urllib import urlopen

from PyQt4.QtCore import pyqtSlot
Expand Down Expand Up @@ -56,8 +53,8 @@ def __init__(self, iface, tableName, user, apiKey, owner=None, sql=None, geoJSON
# SQLite available?
driverName = "SQLite"
sqLiteDrv = ogr.GetDriverByName(driverName)
self.databasePath = QgisCartoDB.CartoDBPlugin.PLUGIN_DIR + '/db/database.sqlite'
self.datasource = sqLiteDrv.Open(self.databasePath, True)
self.database_path = QgisCartoDB.CartoDBPlugin.PLUGIN_DIR + '/db/database.sqlite'
self.datasource = sqLiteDrv.Open(self.database_path, True)
self.layerName = tableName
self.cartoTable = tableName

Expand Down Expand Up @@ -127,7 +124,7 @@ def _loadData(self, sql, geoJSON=None, spatiaLite=None):
if newLyr is not None:
QgsMessageLog.logMessage('New Layer created', 'CartoDB Plugin', QgsMessageLog.INFO)
uri = QgsDataSourceURI()
uri.setDatabase(self.databasePath)
uri.setDatabase(self.database_path)
uri.setDataSource('', self.layerName, 'geometry')
QgsMessageLog.logMessage('New Connection: ' + uri.uri(), 'CartoDB Plugin', QgsMessageLog.INFO)
path = uri.uri()
Expand Down Expand Up @@ -190,14 +187,16 @@ def _uneditableFields(self):
if pgField['data_type'] == 'timestamp with time zone':
self.setEditorWidgetV2(self.fieldNameIndex(pgField['column_name']), 'DateTime')
self.setEditorWidgetV2Config(self.fieldNameIndex(pgField['column_name']), {
u'display_format': u'yyyy-MM-dd hh:mm:ss',
u'field_format': u'yyyy-MM-dd hh:mm:ss',
u'calendar_popup': True})
u'display_format': u'yyyy-MM-dd hh:mm:ss',
u'field_format': u'yyyy-MM-dd hh:mm:ss',
u'calendar_popup': True
})
elif pgField['data_type'] == 'boolean':
self.setEditorWidgetV2(self.fieldNameIndex(pgField['column_name']), 'CheckBox')
self.setEditorWidgetV2Config(self.fieldNameIndex(pgField['column_name']), {
u'CheckedState': u'true',
u'UncheckedState': u'false'})
u'CheckedState': u'true',
u'UncheckedState': u'false'
})
except CartoDBException as e:
QgsMessageLog.logMessage(errorMsg + ' - ' + str(e), 'CartoDB Plugin', QgsMessageLog.CRITICAL)

Expand Down
3 changes: 3 additions & 0 deletions pylintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[FORMAT]
# Maximum number of characters on a single line.
max-line-length = 150
2 changes: 1 addition & 1 deletion ui/Upload.ui
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@
<bool>true</bool>
</property>
<property name="text">
<string>Add CartoDB layer to project</string>
<string>Add CartoDB layer to project (this could truncate the column's names)</string>
</property>
<property name="checked">
<bool>true</bool>
Expand Down

0 comments on commit 2998433

Please sign in to comment.