Skip to content

Commit b243d3e

Browse files
committed
use qgis network stack
1 parent 81421e1 commit b243d3e

File tree

1 file changed

+43
-64
lines changed

1 file changed

+43
-64
lines changed

planet_explorer/planet_api/p_client.py

Lines changed: 43 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
# This will get replaced with a git SHA1 when you do a git archive
2222
__revision__ = "$Format:%H$"
2323

24+
import gzip
2425
import os
2526
import re
2627
import logging
@@ -31,11 +32,11 @@
3132
Optional,
3233
List,
3334
)
34-
from urllib.parse import urlparse
35-
import urllib
36-
from qgis.PyQt.QtCore import pyqtSignal, pyqtSlot, QObject, QSettings
37-
from qgis.core import QgsAuthMethodConfig, QgsApplication, QgsMessageLog, Qgis
35+
from qgis.PyQt.QtCore import pyqtSignal, pyqtSlot, QObject, QUrl
36+
from PyQt5.QtNetwork import QNetworkRequest
37+
from qgis.core import QgsBlockingNetworkRequest
3838

39+
import requests
3940

4041
from planet.api import ClientV1, auth
4142
from planet.api import models as api_models
@@ -62,6 +63,43 @@ class LoginException(Exception):
6263
pass
6364

6465

66+
class QGISAdapter:
67+
def send(self, request: requests.PreparedRequest, **kwargs):
68+
req = QNetworkRequest(QUrl(request.url))
69+
for h in request.headers:
70+
req.setRawHeader(h.encode(), request.headers[h].encode())
71+
req.setRawHeader("Accept-Encoding".encode(), "gzip".encode())
72+
73+
breq = QgsBlockingNetworkRequest()
74+
if request.method == "GET":
75+
error = breq.get(req)
76+
elif request.method == "POST":
77+
body = request.body
78+
if not isinstance(body, bytes):
79+
body = body.encode()
80+
error = breq.post(req, body)
81+
if error > 0:
82+
msg = breq.errorMessage()
83+
if error == 1:
84+
raise requests.exceptions.ConnectionError(msg)
85+
elif error == 2:
86+
raise requests.exceptions.ConnectTimeout(msg)
87+
elif error == 3:
88+
raise requests.exceptions.RequestException(msg)
89+
90+
content = breq.reply()
91+
resp = requests.Response()
92+
for h in content.rawHeaderList():
93+
header = h.data().decode()
94+
resp.headers[header] = content.rawHeader(h).data().decode()
95+
data = content.content().data()
96+
if resp.headers["Content-Encoding"] == "gzip":
97+
data = gzip.decompress(data)
98+
resp._content = data
99+
resp.status_code = content.attribute(QNetworkRequest.HttpStatusCodeAttribute)
100+
return resp
101+
102+
65103
class PlanetClient(QObject, ClientV1):
66104
"""
67105
Wrapper class for ``planet`` Python package, to abstract calls and make it
@@ -77,7 +115,6 @@ def getInstance():
77115
if PlanetClient.__instance is None:
78116
PlanetClient()
79117

80-
PlanetClient.__instance.set_proxy_values()
81118
return PlanetClient.__instance
82119

83120
def __init__(self):
@@ -101,65 +138,7 @@ def __init__(self):
101138
self._item_types = None
102139
self._bundles = None
103140
self._asset_types = {}
104-
105-
def set_proxy_values(self):
106-
settings = QSettings()
107-
proxyEnabled = settings.value("proxy/proxyEnabled")
108-
base_url = self.base_url.lower()
109-
excluded = False
110-
noProxyUrls = settings.value("proxy/noProxyUrls") or []
111-
excluded = any([base_url.startswith(url.lower()) for url in noProxyUrls])
112-
if proxyEnabled and not excluded:
113-
proxyType = settings.value("proxy/proxyType")
114-
if proxyType == "DefaultProxy":
115-
# Try to get system proxy settings
116-
117-
proxies = urllib.request.getproxies()
118-
proxy_url = proxies.get("http") or proxies.get("https")
119-
if proxy_url:
120-
# Parse proxy_url, e.g. http://host:port
121-
parsed = urlparse(proxy_url)
122-
proxyHost = parsed.hostname
123-
proxyPort = parsed.port
124-
else:
125-
QgsMessageLog.logMessage(
126-
"Planet Explorer: No system proxy found for 'DefaultProxy' proxy type.",
127-
level=Qgis.Warning,
128-
)
129-
return
130-
elif proxyType == "HttpProxy":
131-
proxyHost = settings.value("proxy/proxyHost")
132-
proxyPort = settings.value("proxy/proxyPort")
133-
else:
134-
QgsMessageLog.logMessage(
135-
"Planet Explorer: Only 'HttpProxy' or 'Default' "
136-
"QGIS Proxy options are supported "
137-
"for connecting to the Planet API.",
138-
level=Qgis.Warning,
139-
)
140-
return
141-
142-
url = f"{proxyHost}:{proxyPort}" # noqa
143-
authid = settings.value("proxy/authcfg", "")
144-
if authid:
145-
authConfig = QgsAuthMethodConfig()
146-
QgsApplication.authManager().loadAuthenticationConfig(
147-
authid, authConfig, True
148-
)
149-
username = authConfig.config("username")
150-
password = authConfig.config("password")
151-
else:
152-
username = settings.value("proxy/proxyUser")
153-
password = settings.value("proxy/proxyPassword")
154-
155-
if username:
156-
tokens = url.split("://")
157-
url = f"{tokens[0]}://{username}:{password}@{tokens[-1]}" # noqa: E231
158-
159-
self.dispatcher.session.proxies["http"] = url
160-
self.dispatcher.session.proxies["https"] = url
161-
else:
162-
self.dispatcher.session.proxies = {}
141+
self.dispatcher.session.mount("https://", QGISAdapter())
163142

164143
@waitcursor
165144
def log_in(self, user, password, api_key=None):

0 commit comments

Comments
 (0)