Skip to content

Commit

Permalink
fixing import issues to QGIS3 and Python3 compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonSAMPERE committed May 27, 2019
1 parent 28e8cd4 commit 7bc9d8f
Show file tree
Hide file tree
Showing 8 changed files with 72 additions and 85 deletions.
14 changes: 6 additions & 8 deletions __init__.py
Expand Up @@ -25,11 +25,9 @@

# noinspection PyPep8Naming
def classFactory(iface): # pylint: disable=invalid-name
"""Load Isogeo class from file Isogeo.
:param iface: A QGIS interface instance.
:type iface: QgsInterface
"""
#
from isogeo import Isogeo
return Isogeo(iface)
"""Load Isogeo class from file Isogeo.
:param iface: A QGIS interface instance.
:type iface: QgsInterface
"""
from .isogeo import Isogeo
return Isogeo(iface)
93 changes: 41 additions & 52 deletions isogeo.py
Expand Up @@ -33,42 +33,47 @@
from logging.handlers import RotatingFileHandler
from collections import OrderedDict
from functools import partial
import sys

# PyQT
# from QByteArray
from qgis.PyQt.QtCore import (QByteArray, QCoreApplication, QSettings,
Qt, QTranslator, QUrl, qVersion)
from qgis.PyQt.QtGui import (QAction, QComboBox, QIcon, QMessageBox,
QStandardItemModel, QStandardItem, QProgressBar)
from qgis.PyQt.QtCore import (
QByteArray, QCoreApplication, QSettings, Qt, QTranslator, QUrl, qVersion)

from qgis.PyQt.QtWidgets import QAction, QComboBox, QMessageBox, QProgressBar
from qgis.PyQt.QtGui import QIcon, QStandardItemModel, QStandardItem

from qgis.PyQt.QtNetwork import QNetworkRequest

# PyQGIS
import db_manager.db_plugins.postgis.connector as pgis_con
from qgis.utils import iface, plugin_times, QGis
from qgis.core import (QgsCoordinateReferenceSystem, QgsCoordinateTransform,
QgsDataSourceURI,
QgsMapLayerRegistry, QgsMessageLog,
QgsNetworkAccessManager,
QgsPoint, QgsRectangle, QgsRasterLayer, QgsVectorLayer)

from qgis.utils import iface, plugin_times

from qgis.core import (QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsDataSourceUri, QgsMessageLog,
QgsNetworkAccessManager, QgsPoint, QgsRectangle, QgsRasterLayer, QgsVectorLayer, QgsProject)

try:
from qgis.core import Qgis
except ImportError:
from qgis.core import QGis as Qgis

# Initialize Qt resources from file resources.py
import resources
from . import resources

# UI classes
from ui.isogeo_dockwidget import IsogeoDockWidget # main widget
from ui.auth.dlg_authentication import IsogeoAuthentication
from ui.credits.dlg_credits import IsogeoCredits
from ui.metadata.dlg_md_details import IsogeoMdDetails
from ui.quicksearch.dlg_quicksearch_new import QuicksearchNew
from ui.quicksearch.dlg_quicksearch_rename import QuicksearchRename
from .ui.isogeo_dockwidget import IsogeoDockWidget # main widget
from .ui.auth.dlg_authentication import IsogeoAuthentication
from .ui.credits.dlg_credits import IsogeoCredits
from .ui.metadata.dlg_md_details import IsogeoMdDetails
from .ui.quicksearch.dlg_quicksearch_new import QuicksearchNew
from .ui.quicksearch.dlg_quicksearch_rename import QuicksearchRename

# Plugin modules
from modules import IsogeoPlgApiMngr
from modules import MetadataDisplayer
from modules import ResultsManager
from modules import IsogeoPlgTools
from modules import UrlBuilder
from .modules import IsogeoPlgApiMngr
from .modules import MetadataDisplayer
from .modules import ResultsManager
from .modules import IsogeoPlgTools
from .modules import UrlBuilder

# ############################################################################
# ########## Globals ###############
Expand All @@ -78,10 +83,6 @@
plg_basepath = os.path.dirname(os.path.realpath(__file__))
plg_reg_name = os.path.basename(plg_basepath)

# force encoding
reload(sys)
sys.setdefaultencoding('utf-8')

# QGIS useful tooling and shortcuts
msgBar = iface.messageBar()
qsettings = QSettings()
Expand All @@ -106,11 +107,10 @@
# log level depends on plugin directory name
if plg_reg_name == plg_tools.plugin_metadata(base_path=plg_basepath, value="name"):
log_level = logging.WARNING
elif "beta" in plg_tools.plugin_metadata(base_path=plg_basepath)\
or "dev" in plg_tools.plugin_metadata(base_path=plg_basepath, value="name"):
elif "beta" in plg_tools.plugin_metadata(base_path=plg_basepath) or "dev" in plg_tools.plugin_metadata(base_path=plg_basepath, value="name"):
log_level = logging.DEBUG
else:
log_level = logging.DEBUG
log_level = logging.INFO

logger = logging.getLogger("IsogeoQgisPlugin")
logging.captureWarnings(True)
Expand Down Expand Up @@ -155,7 +155,7 @@ class Isogeo:

logger.info('\n\n\t========== Isogeo Search Engine for QGIS ==========')
logger.info('OS: {0}'.format(platform.platform()))
logger.info('QGIS Version: {0}'.format(QGis.QGIS_VERSION))
logger.info('QGIS Version: {0}'.format(Qgis.QGIS_VERSION))
logger.info('Plugin version: {0}'.format(plg_version))
logger.info('Log level: {0}'.format(log_level))

Expand Down Expand Up @@ -765,8 +765,7 @@ def update_fields(self, result):
with open(self.json_path) as data_file:
saved_searches = json.load(data_file)
search_params = saved_searches.get(self.savedSearch)
keywords_list = [v for k,v in search_params.items()\
if k.startswith("keyword")]
keywords_list = [v for k,v in search_params.items() if k.startswith("keyword")]
self.update_cbb_keywords(tags_keywords=tags.get('keywords'),
selected_keywords=keywords_list)
# Putting widgets to their previous states according
Expand Down Expand Up @@ -1563,9 +1562,7 @@ def add_layer(self, layer_info):
lyr.setAbstract(layer_info.get("abstract", ""))
lyr.setKeywordList(",".join(layer_info.get("keywords", ())))
logger.debug("Data added: {}".format(table))
elif not layer.isValid() and\
plg_tools.last_error[0] == "postgis" and\
"prim" in plg_tools.last_error[1]:
elif not layer.isValid() and plg_tools.last_error[0] == "postgis" and "prim" in plg_tools.last_error[1]:
logger.debug("PostGIS layer may be a view, "
"so key column is missing. "
"Trying to automatically set one...")
Expand Down Expand Up @@ -1670,8 +1667,7 @@ def send_details_request(self, md_id):
:param str md_id: UUID of metadata to retrieve
"""
logger.debug("Full metatada sheet asked. Building the url.")
self.currentUrl = "{}/resources/{}{}"\
.format(plg_api_mngr.api_url_base,
self.currentUrl = "{}/resources/{}{}".format(plg_api_mngr.api_url_base,
md_id,
"?_include=conditions,contacts,"
"coordinate-system,events,"
Expand Down Expand Up @@ -1714,32 +1710,25 @@ def write_shares_info(self, content):
# Isogeo application authenticated in the plugin
app = content[0].get("applications")[0]
text += self.tr(u"<p>This plugin is authenticated as "
u"<a href='{}'>{}</a> and ")\
.format(app.get("url", "https://isogeo.gitbooks.io/app-plugin-qgis/content"),
u"<a href='{}'>{}</a> and ").format(app.get("url", "https://isogeo.gitbooks.io/app-plugin-qgis/content"),
app.get("name", "Isogeo plugin for QGIS"))
# shares feeding the application
if len(content) == 1:
text += self.tr(u" powered by 1 share:</p></br>")
else:
text += self.tr(u" powered by {0} shares:</p></br>")\
.format(len(content))
text += self.tr(u" powered by {0} shares:</p></br>").format(len(content))
# shares details
for share in sorted(content):
# share variables
creator_name = share.get("_creator").get("contact").get("name")
creator_email = share.get("_creator").get("contact").get("email")
creator_id = share.get("_creator").get("_tag")[6:]
share_url = "https://app.isogeo.com/groups/{}/admin/shares/{}"\
.format(creator_id, share.get("_id"))
share_url = "https://app.isogeo.com/groups/{}/admin/shares/{}".format(creator_id, share.get("_id"))
# formatting text
text += u"<p><a href='{}'><b>{}</b></a></p>"\
.format(share_url,
text += u"<p><a href='{}'><b>{}</b></a></p>".format(share_url,
share.get("name"))
text += self.tr(u"<p>Updated: {}</p>")\
.format(plg_tools.handle_date(share.get("_modified")))
text += self.tr(u"<p>Contact: {} - {}</p>")\
.format(creator_name,
creator_email)
text += self.tr(u"<p>Updated: {}</p>").format(plg_tools.handle_date(share.get("_modified")))
text += self.tr(u"<p>Contact: {} - {}</p>").format(creator_name, creator_email)
text += u"<p><hr></p>"
text += u"</html>"
self.dockwidget.txt_shares.setText(text)
Expand Down Expand Up @@ -1840,7 +1829,7 @@ def run(self):
link=u"https://github.com/isogeo/isogeo-plugin-qgis/issues/new?title={} - plugin v{} QGIS {} ({})&labels=bug&milestone=4"
.format(self.tr("TITLE ISSUE REPORTED"),
plg_tools.plugin_metadata(base_path=plg_basepath),
QGis.QGIS_VERSION,
Qgis.QGIS_VERSION,
platform.platform())
))
# help button
Expand Down
10 changes: 5 additions & 5 deletions modules/__init__.py
@@ -1,5 +1,5 @@
from api import IsogeoPlgApiMngr
from metadata_display import MetadataDisplayer
from results import ResultsManager
from tools import IsogeoPlgTools
from url_builder import UrlBuilder
from .api import IsogeoPlgApiMngr
from .metadata_display import MetadataDisplayer
from .results import ResultsManager
from .tools import IsogeoPlgTools
from .url_builder import UrlBuilder
2 changes: 1 addition & 1 deletion modules/api.py
Expand Up @@ -9,7 +9,7 @@

# PyQT
from qgis.PyQt.QtCore import QSettings
from qgis.PyQt.QtGui import QMessageBox
from qgis.PyQt.QtWidgets import QMessageBox

# Plugin modules
from .tools import IsogeoPlgTools
Expand Down
10 changes: 5 additions & 5 deletions modules/metadata_display.py
Expand Up @@ -7,14 +7,14 @@
from datetime import datetime

# PyQGIS
from qgis.core import (QgsMapLayerRegistry, QgsMessageLog,
QgsVectorLayer, QgsPoint, QgsRectangle, QgsFeature,
QgsGeometry, QgsRasterLayer)
from qgis.gui import QgsMapCanvasLayer
from qgis.core import (QgsProject, QgsMessageLog, QgsVectorLayer, QgsPoint,
QgsRectangle, QgsFeature, QgsGeometry, QgsRasterLayer)


# PyQT
from qgis.PyQt.QtCore import QSettings, Qt
from qgis.PyQt.QtGui import QColor, QTableWidgetItem
from qgis.PyQt.QtGui import QColor
from qgis.PyQt.QtWidgets import QTableWidgetItem

# 3rd party
from .isogeo_pysdk import IsogeoTranslator
Expand Down
6 changes: 3 additions & 3 deletions modules/results.py
Expand Up @@ -11,9 +11,9 @@
# PyQT
# from QByteArray
from qgis.PyQt.QtCore import QSettings
from qgis.PyQt.QtGui import (QIcon, QTableWidgetItem, QComboBox, QPushButton,
QLabel, QPixmap, QProgressBar, QHeaderView)

from qgis.PyQt.QtGui import QIcon, QPixmap
from qgis.PyQt.QtWidgets import (QTableWidgetItem, QComboBox, QPushButton, QLabel,
QProgressBar, QHeaderView)
# PyQGIS
from qgis.utils import iface

Expand Down
13 changes: 6 additions & 7 deletions modules/tools.py
Expand Up @@ -3,24 +3,23 @@
print_function, unicode_literals)

# Standard library
import ConfigParser
import configparser
import datetime
import logging
from os import access, path, R_OK
import subprocess
from sys import platform as opersys
from urllib import getproxies, unquote, urlencode
from urlparse import urlparse
from urllib.request import getproxies, unquote
from urllib.parse import urlencode, urlparse
import webbrowser

# PyQGIS
from qgis.core import (QgsDataSourceURI, QgsProject,
QgsVectorLayer, QgsMapLayerRegistry, QgsRasterLayer)
from qgis.core import (QgsDataSourceUri, QgsProject, QgsVectorLayer, QgsProject, QgsRasterLayer)
from qgis.utils import iface

# PyQT
from qgis.PyQt.QtCore import QSettings, QUrl
from qgis.PyQt.QtGui import QMessageBox
from qgis.PyQt.QtWidgets import QMessageBox

# Depending on operating system
if opersys == 'win32':
Expand Down Expand Up @@ -205,7 +204,7 @@ def plugin_metadata(self, base_path=path.dirname(__file__), section="general", v
* tracker
* repository
"""
config = ConfigParser.ConfigParser()
config = configparser.ConfigParser()
if path.isfile(path.join(base_path, 'metadata.txt')):
config.read(path.join(base_path, 'metadata.txt'))
return config.get('general', value)
Expand Down
9 changes: 5 additions & 4 deletions modules/url_builder.py
Expand Up @@ -5,13 +5,14 @@
# Standard library
import logging
import re
from urllib import unquote, urlencode
from urllib.request import unquote
from urllib.parse import urlencode

# PyQT
from qgis.PyQt.QtCore import QSettings

# QGIS
from qgis.core import QgsDataSourceURI
from qgis.core import QgsDataSourceUri

# Plugin modules
from .tools import IsogeoPlgTools
Expand Down Expand Up @@ -54,9 +55,9 @@
from owslib.util import HTTPError
logger.info("Depencencies - HTTPError within owslib")
except ImportError as e:
from urllib2 import HTTPError
from urllib.error import HTTPError
logger.warning("Depencencies - HTTPError not within owslib."
" Directly imported from urllib2.")
" Directly imported from urllib.error")
try:
import requests
logger.info("Depencencies - Requests version: {}"
Expand Down

0 comments on commit 7bc9d8f

Please sign in to comment.