Skip to content

Commit ac23d85

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

File tree

1 file changed

+42
-64
lines changed

1 file changed

+42
-64
lines changed

planet_explorer/planet_api/p_client.py

Lines changed: 42 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
@@ -61,6 +62,42 @@ class LoginException(Exception):
6162

6263
pass
6364

65+
class QGISAdapter:
66+
def send(self, request: requests.PreparedRequest, **kwargs):
67+
req = QNetworkRequest(QUrl(request.url))
68+
for h in request.headers:
69+
req.setRawHeader(h.encode(), request.headers[h].encode())
70+
req.setRawHeader("Accept-Encoding".encode(), "gzip".encode())
71+
72+
breq = QgsBlockingNetworkRequest()
73+
if request.method == "GET":
74+
error = breq.get(req)
75+
elif request.method == "POST":
76+
body = request.body
77+
if not isinstance(body, bytes):
78+
body = body.encode()
79+
error = breq.post(req, body)
80+
if error > 0:
81+
msg = breq.errorMessage()
82+
if error == 1:
83+
raise requests.exceptions.ConnectionError(msg)
84+
elif error == 2:
85+
raise requests.exceptions.ConnectTimeout(msg)
86+
elif error == 3:
87+
raise requests.exceptions.RequestException(msg)
88+
89+
content = breq.reply()
90+
resp = requests.Response()
91+
for h in content.rawHeaderList():
92+
header = h.data().decode()
93+
resp.headers[header] = content.rawHeader(h).data().decode()
94+
data = content.content().data()
95+
if resp.headers["Content-Encoding"] == "gzip":
96+
data = gzip.decompress(data)
97+
resp._content = data
98+
resp.status_code = content.attribute(QNetworkRequest.HttpStatusCodeAttribute)
99+
return resp
100+
64101

65102
class PlanetClient(QObject, ClientV1):
66103
"""
@@ -77,7 +114,6 @@ def getInstance():
77114
if PlanetClient.__instance is None:
78115
PlanetClient()
79116

80-
PlanetClient.__instance.set_proxy_values()
81117
return PlanetClient.__instance
82118

83119
def __init__(self):
@@ -101,65 +137,7 @@ def __init__(self):
101137
self._item_types = None
102138
self._bundles = None
103139
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 = {}
140+
self.dispatcher.session.mount("https://", QGISAdapter())
163141

164142
@waitcursor
165143
def log_in(self, user, password, api_key=None):

0 commit comments

Comments
 (0)