Skip to content

Commit

Permalink
fix python2 refs
Browse files Browse the repository at this point in the history
  • Loading branch information
Guts committed Sep 12, 2019
1 parent 21b96db commit 50f8f5d
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 63 deletions.
50 changes: 26 additions & 24 deletions tests/dev/dev_download_file.py
Expand Up @@ -10,37 +10,38 @@

qsettings = QSettings()
api_id = qsettings.value("isogeo-plugin/user-auth/id", 0)
api_secret = qsettings.value("isogeo-plugin/user-auth/secret", 0)
api_secret = qsettings.value("isogeo-plugin/user-auth/secret", 0)
manager = QNetworkAccessManager()

# -- FUNCTIONS ---------------------------------------------


def ask_for_token(c_id, c_secret, request_status=True):
"""Ask a token from Isogeo API authentification page.
"""Ask a token from Isogeo API authentification page.
This send a POST request to Isogeo API with the user id and secret in
its header. The API should return an access token
"""
headervalue = "Basic " + base64.b64encode(c_id + ":" + c_secret)
data = urllib.urlencode({"grant_type": "client_credentials"})
databyte = QByteArray()
databyte.append(data)
url = QUrl('https://id.api.isogeo.com/oauth/token')
request = QNetworkRequest(url)
request.setRawHeader("Authorization", headervalue)
if request_status is True:
request_status = False
return request, databyte

headervalue = "Basic " + base64.b64encode(c_id + ":" + c_secret)
data = urllib.urlencode({"grant_type": "client_credentials"})
databyte = QByteArray()
databyte.append(data)
url = QUrl("https://id.api.isogeo.com/oauth/token")
request = QNetworkRequest(url)
request.setRawHeader("Authorization", headervalue)
if request_status is True:
request_status = False
return request, databyte

QgsMessageLog.logMessage("Authentication succeeded", "Isogeo")
QgsMessageLog.logMessage("Authentication succeeded", "Isogeo")


def request_download(manager, target_url):
url = QUrl(target_url)
request = QNetworkRequest(url)
print("Download start time: {}".format(datetime.now()))
manager.get( request )
manager.get(request)


def handle_download(reply):
print("Download finish time: {}".format(datetime.now()))
Expand All @@ -49,8 +50,8 @@ def handle_download(reply):
print(type(reply), dir(reply), help(reply.write))
url = reply.url().path()
print(url)
# with open("C:\Users\julien.moura\Documents\GIS DataBase\youhou.xml", "wb") as fifi:
# fifi.write(reply.writeData())
# with open("C:\Users\julien.moura\Documents\GIS DataBase\youhou.xml", "wb") as fifi:
# fifi.write(reply.writeData())
newFile = QFile()
newFile.setFileName(".\youhou_2.htm")
newFile.open(QIODevice.WriteOnly)
Expand All @@ -59,28 +60,29 @@ def handle_download(reply):
print("done")
reply.deleteLater()


def read_data(reply):
messageBuffer += reply.readAll()


# ---- Main ----------------------------------------------------


# print(dir(manager))
#manager.finished.connect( handle_download )
# manager.finished.connect( handle_download )

# with a simple web page
#url = "https://www.nextinpact.com/news/103770-google-annonce-android-o-liste-nouveautes-developer-preview-disponible.htm"
#request_download(manager, url)
# url = "https://www.nextinpact.com/news/103770-google-annonce-android-o-liste-nouveautes-developer-preview-disponible.htm"
# request_download(manager, url)

# with an authenticated API request
req_token = ask_for_token(api_id, api_secret)
token_reply = manager.post(req_token[0], req_token[1])
#token_reply.finished.connect(
# token_reply.finished.connect(
# partial(self.handle_token, answer=token_reply))
token_reply.finished.connect(
partial(self.handle_token, answer=token_reply))
token_reply.finished.connect(partial(self.handle_token, answer=token_reply))
bytarray = token_reply.readAll()
print("bbibit", bytarray, dir(bytarray))
content = str(bytarray)
parsed_content = json.loads(QByteArray.fromBase64(bytarray))
print(parsed_content)
print(parsed_content)
92 changes: 53 additions & 39 deletions tests/dev/qgis_console/dev_wmts.py
Expand Up @@ -9,33 +9,37 @@
from owslib.wmts import WebMapTileService
from owslib.util import ServiceException
import owslib
print("Depencencies - owslib version: {}"
.format(owslib.__version__))

print("Depencencies - owslib version: {}".format(owslib.__version__))
except ImportError as e:
print("Depencencies - owslib is not present")

try:
from owslib.util import HTTPError

print("Depencencies - HTTPError within owslib")
except ImportError as e:
print("Depencencies - HTTPError not within owslib."
" Trying to get it from urllib2 directly.")
print(
"Depencencies - HTTPError not within owslib."
" Trying to get it from urllib2 directly."
)
from urllib2 import HTTPError

# ################################
# ######## Variables ###############
# ################################

current_crs = str(iface.mapCanvas()
.mapRenderer()
.destinationCrs()
.authid())
current_crs = str(iface.mapCanvas().mapRenderer().destinationCrs().authid())

qgis_wms_formats = ('image/png', 'image/png8',
'image/jpeg',
'image/svg',
'image/gif',
'image/geotiff', 'image/tiff')
qgis_wms_formats = (
"image/png",
"image/png8",
"image/jpeg",
"image/svg",
"image/gif",
"image/geotiff",
"image/tiff",
)

# ################################
# ######## Script #################
Expand All @@ -44,13 +48,19 @@
QgsMapLayerRegistry.instance().removeAllMapLayers()

# sample WMTS
wmts_url_in_public_1 = "http://suite.opengeo.org/geoserver/gwc/service/wmts?request=getcapabilities" # bd_lyr = "opengeo:countries"
wmts_url_in_public_2 = "http://noisy.hq.isogeo.fr:6090/geoserver/gwc/service/wmts?REQUEST=GetCapabilities" # i_lyr = "Isogeo:WC2014_stadiums"
wmts_url_in_public_1 = (
"http://suite.opengeo.org/geoserver/gwc/service/wmts?request=getcapabilities"
) # bd_lyr = "opengeo:countries"
wmts_url_in_public_2 = (
"http://noisy.hq.isogeo.fr:6090/geoserver/gwc/service/wmts?REQUEST=GetCapabilities"
) # i_lyr = "Isogeo:WC2014_stadiums"
wmts_url_in_public_3 = "http://opencache.statkart.no/gatekeeper/gk/gk.open_wmts?service=WMTS&request=GetCapabilities" # msc_lyr = "Europakart"
wmts_url_in_public_4_esri = "http://data.geus.dk/arcgis/rest/services/OneGeologyGlobal/S071_G2500_OneGeology/MapServer/WMTS?request=GetCapabilities"
wmts_url_in_public_5_esri = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/WMTS?REQUEST=GetCapabilities&SERVICE=WMTS"
wmts_url_in_publc_6 = "http://openlayers.org/en/v4.0.1/examples/data/WMTSCapabilities.xml?request=GetCapabilities&service=WMTS"
wmts_url_in_publc_7 = "https://www.ppige-npdc.fr/geoserver/gwc/service/wmts?REQUEST=GetCapabilities"
wmts_url_in_publc_7 = (
"https://www.ppige-npdc.fr/geoserver/gwc/service/wmts?REQUEST=GetCapabilities"
)

# opening WMTS
wmts_url_getcap = wmts_url_in_public_1
Expand All @@ -64,18 +74,18 @@
print("WMTS - Bad operation: " + wmts_url_getcap, str(e))
except HTTPError as e:
print("WMTS - Service not reached: " + wmts_url_getcap, str(e))
except Exception, e:
except Exception as e:
print(str(e))
tout

print(dir(wmts))
#'buildTileRequest', 'contents', 'getOperationByName', 'getServiceXML', 'getfeatureinfo',
#'buildTileRequest', 'contents', 'getOperationByName', 'getServiceXML', 'getfeatureinfo',
#'gettile', 'identification', 'items', 'operations', 'password', 'provider',
#'serviceMetadataURL', 'themes', 'tilematrixsets', 'url', 'username', 'version']

# service responsible
#print(wmts.provider.name, wmts.provider.url)
#print("Contact: ", wmts.provider.contact.name,
# print(wmts.provider.name, wmts.provider.url)
# print("Contact: ", wmts.provider.contact.name,
# wmts.provider.contact.email,
# wmts.provider.contact.position,
# wmts.provider.contact.organization,
Expand All @@ -102,7 +112,11 @@


# Tile Matrix Set & SRS
print("Available tile matrix sets: ", wmts_lyr.tilematrixsets, type(wmts_lyr.tilematrixsets))
print(
"Available tile matrix sets: ",
wmts_lyr.tilematrixsets,
type(wmts_lyr.tilematrixsets),
)
def_tile_matrix_set = wmts_lyr.tilematrixsets[0]
print(dir(def_tile_matrix_set))

Expand All @@ -124,9 +138,8 @@
srs = tile_matrix_set

# Format definition
wmts_lyr_formats = wmts.getOperationByName('GetTile').formatOptions
formats_image = [f.split(" ", 1)[0] for f in wmts_lyr_formats
if f in qgis_wms_formats]
wmts_lyr_formats = wmts.getOperationByName("GetTile").formatOptions
formats_image = [f.split(" ", 1)[0] for f in wmts_lyr_formats if f in qgis_wms_formats]
if len(formats_image):
if "image/png" in formats_image:
layer_format = "image/png"
Expand All @@ -143,41 +156,42 @@
lyr_style = wmts_lyr.styles.keys()[0]

# Themes listing
#print("Available themes: ", wmts.themes)
#lyr_themes = wmts.themes.keys()[0]
# print("Available themes: ", wmts.themes)
# lyr_themes = wmts.themes.keys()[0]


# GetTile URL
wmts_lyr_url = wmts.getOperationByName('GetTile').methods
wmts_lyr_url = wmts.getOperationByName("GetTile").methods
wmts_lyr_url = wmts_lyr_url[0].get("url")
if wmts_lyr_url[-1] == "&":
wmts_lyr_url = wmts_lyr_url[:-1]
else:
pass

# URL construction
wmts_url_params = {"SERVICE": "WMTS",
"VERSION": "1.0.0",
"REQUEST": "GetCapabilities",
"layers": layer_id,
"crs": srs,
"format": layer_format,
"styles": "",
"tileMatrixSet": tile_matrix_set,
"url": wmts_lyr_url,
}
wmts_url_params = {
"SERVICE": "WMTS",
"VERSION": "1.0.0",
"REQUEST": "GetCapabilities",
"layers": layer_id,
"crs": srs,
"format": layer_format,
"styles": "",
"tileMatrixSet": tile_matrix_set,
"url": wmts_lyr_url,
}
wmts_url_final = unquote(urlencode(wmts_url_params))
print(wmts_url_final)

# let's try to add it to the map canvas
qgis_wmts_lyr_manual = QgsRasterLayer(wmts_url_final, "Auto - " + layer_title, 'wms')
qgis_wmts_lyr_manual = QgsRasterLayer(wmts_url_final, "Auto - " + layer_title, "wms")
if qgis_wmts_lyr_manual.isValid():
QgsMapLayerRegistry.instance().addMapLayer(qgis_wmts_lyr_manual)
else:
print(qgis_wmts_lyr_manual.error().message())

manual_lyr = "contextualWMSLegend=0&crs=EPSG:4326&dpiMode=7&featureCount=10&format=image/jpeg&layers=usa:states&styles=&tileMatrixSet=EPSG:4326&url=http://suite.opengeo.org/geoserver/gwc/service/wmts?request%3DGetCapabilities"
qgis_wmts_lyr = QgsRasterLayer(manual_lyr, "Manual - " + layer_title, 'wms')
qgis_wmts_lyr = QgsRasterLayer(manual_lyr, "Manual - " + layer_title, "wms")
if qgis_wmts_lyr.isValid():
QgsMapLayerRegistry.instance().addMapLayer(qgis_wmts_lyr)
pass
Expand Down

0 comments on commit 50f8f5d

Please sign in to comment.