2222"""
2323
2424
25- __author__ = ' Alessandro Pasotti'
26- __date__ = ' August 2016'
25+ __author__ = " Alessandro Pasotti"
26+ __date__ = " August 2016"
2727
2828import sys
29-
30- from qgis .PyQt .QtCore import QUrl
31- from qgis .PyQt .QtCore import pyqtSlot , QEventLoop
32- from qgis .PyQt .QtNetwork import QNetworkRequest , QNetworkReply
3329import urllib
3430
35- from qgis .core import QgsNetworkAccessManager , QgsAuthManager , QgsMessageLog
31+ from qgis .core import QgsAuthManager , QgsMessageLog , QgsNetworkAccessManager
32+ from qgis .PyQt .QtCore import QEventLoop , QUrl
33+ from qgis .PyQt .QtNetwork import QNetworkReply , QNetworkRequest
3634
3735# FIXME: ignored
3836DEFAULT_MAX_REDIRECTS = 4
3937
38+
4039class RequestsException (Exception ):
4140 pass
4241
42+
4343class RequestsExceptionTimeout (RequestsException ):
4444 pass
4545
46+
4647class RequestsExceptionConnectionError (RequestsException ):
4748 pass
4849
50+
4951class Map (dict ):
5052 """
5153 Example:
5254 m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
5355 """
56+
5457 def __init__ (self , * args , ** kwargs ):
5558 super (Map , self ).__init__ (* args , ** kwargs )
5659 for arg in args :
@@ -83,9 +86,11 @@ def __delitem__(self, key):
8386class Response (Map ):
8487 pass
8588
89+
8690PYTHON_VERSION = sys .version_info [0 ]
8791
88- class NetworkAccessManager ():
92+
93+ class NetworkAccessManager :
8994 """
9095 This class mimicks httplib2 by using QgsNetworkAccessManager for all
9196 network calls.
@@ -114,8 +119,13 @@ class NetworkAccessManager():
114119
115120 """
116121
117-
118- def __init__ (self , authid = None , disable_ssl_certificate_validation = False , exception_class = None , debug = True ):
122+ def __init__ (
123+ self ,
124+ authid = None ,
125+ disable_ssl_certificate_validation = False ,
126+ exception_class = None ,
127+ debug = True ,
128+ ):
119129 self .disable_ssl_certificate_validation = disable_ssl_certificate_validation
120130 self .authid = authid
121131 self .reply = None
@@ -134,40 +144,55 @@ def msg_log(self, msg):
134144 if self .debug :
135145 QgsMessageLog .logMessage (msg , "NetworkAccessManager" )
136146
137- def request (self , url , method = "GET" , body = None , headers = None , redirections = DEFAULT_MAX_REDIRECTS , connection_type = None , authenticate = True ):
147+ def request (
148+ self ,
149+ url ,
150+ method = "GET" ,
151+ body = None ,
152+ headers = None ,
153+ redirections = DEFAULT_MAX_REDIRECTS ,
154+ connection_type = None ,
155+ authenticate = True ,
156+ ):
138157 """
139158 Make a network request by calling QgsNetworkAccessManager.
140159 redirections argument is ignored and is here only for httplib2 compatibility.
141160 """
142- self .msg_log (u'http_call request: {0}' .format (url ))
143- self .http_call_result = Response ({
144- 'status' : 0 ,
145- 'status_code' : 0 ,
146- 'status_message' : '' ,
147- 'text' : '' ,
148- 'ok' : False ,
149- 'headers' : {},
150- 'reason' : '' ,
151- 'exception' : None ,
152- })
161+ self .msg_log ("http_call request: {0}" .format (url ))
162+ self .http_call_result = Response (
163+ {
164+ "status" : 0 ,
165+ "status_code" : 0 ,
166+ "status_message" : "" ,
167+ "text" : "" ,
168+ "ok" : False ,
169+ "headers" : {},
170+ "reason" : "" ,
171+ "exception" : None ,
172+ }
173+ )
153174 req = QNetworkRequest ()
154- req .setAttribute (QNetworkRequest .CookieSaveControlAttribute , QNetworkRequest .Manual )
155- req .setAttribute (QNetworkRequest .CookieLoadControlAttribute , QNetworkRequest .Manual )
175+ req .setAttribute (
176+ QNetworkRequest .CookieSaveControlAttribute , QNetworkRequest .Manual
177+ )
178+ req .setAttribute (
179+ QNetworkRequest .CookieLoadControlAttribute , QNetworkRequest .Manual
180+ )
156181 # Avoid double quoting form QUrl
157182 url = urllib .parse .unquote (url )
158183 req .setUrl (QUrl (url ))
159184
160185 if self .cookie is not None :
161186 if headers is not None :
162- headers [' Cookie' ] = self .cookie
187+ headers [" Cookie" ] = self .cookie
163188 else :
164- headers = {' Cookie' : self .cookie }
189+ headers = {" Cookie" : self .cookie }
165190
166191 if self .basicauth is not None and authenticate :
167192 if headers is not None :
168- headers [' Authorization' ] = self .basicauth
193+ headers [" Authorization" ] = self .basicauth
169194 else :
170- headers = {' Authorization' : self .basicauth }
195+ headers = {" Authorization" : self .basicauth }
171196
172197 if headers is not None :
173198 # This fixes a wierd error with compressed content not being correctly
@@ -177,36 +202,38 @@ def request(self, url, method="GET", body=None, headers=None, redirections=DEFAU
177202 # encoding processing".
178203 # See: https://bugs.webkit.org/show_bug.cgi?id=63696#c1
179204 try :
180- del headers [' Accept-Encoding' ]
205+ del headers [" Accept-Encoding" ]
181206 except KeyError :
182207 pass
183208 for k , v in headers .items ():
184209 if PYTHON_VERSION >= 3 :
185210 if isinstance (k , str ):
186- k = k .encode (' utf-8' )
211+ k = k .encode (" utf-8" )
187212 if isinstance (v , str ):
188- v = v .encode (' utf-8' )
213+ v = v .encode (" utf-8" )
189214 req .setRawHeader (k , v )
190215
191216 if self .authid :
192217 self .msg_log ("Update request w/ authid: {0}" .format (self .authid ))
193218 QgsAuthManager .instance ().updateNetworkRequest (req , self .authid )
194219 if self .reply is not None and self .reply .isRunning ():
195220 self .reply .close ()
196- if method .lower () == ' delete' :
197- func = getattr (QgsNetworkAccessManager .instance (), ' deleteResource' )
221+ if method .lower () == " delete" :
222+ func = getattr (QgsNetworkAccessManager .instance (), " deleteResource" )
198223 else :
199224 func = getattr (QgsNetworkAccessManager .instance (), method .lower ())
200225 # Calling the server ...
201226 # Let's log the whole call for debugging purposes:
202- self .msg_log ("Sending %s request to %s" % (method .upper (), req .url ().toString ()))
227+ self .msg_log (
228+ "Sending %s request to %s" % (method .upper (), req .url ().toString ())
229+ )
203230 headers = {str (h ): str (req .rawHeader (h )) for h in req .rawHeaderList ()}
204231 for k , v in headers .items ():
205232 self .msg_log ("%s: %s" % (k , v ))
206- if method .lower () in [' post' , ' put' ]:
233+ if method .lower () in [" post" , " put" ]:
207234 if PYTHON_VERSION >= 3 :
208235 if isinstance (body , str ):
209- body = body .encode (' utf-8' )
236+ body = body .encode (" utf-8" )
210237 self .reply = func (req , body )
211238 else :
212239 self .reply = func (req )
@@ -226,11 +253,17 @@ def request(self, url, method="GET", body=None, headers=None, redirections=DEFAU
226253 try :
227254 self .el .exec_ ()
228255 # Let's log the whole response for debugging purposes:
229- self .msg_log ("Got response %s %s from %s" % \
230- (self .http_call_result .status_code ,
231- self .http_call_result .status_message ,
232- self .reply .url ().toString ()))
233- headers = {str (h ): str (self .reply .rawHeader (h )) for h in self .reply .rawHeaderList ()}
256+ self .msg_log (
257+ "Got response %s %s from %s"
258+ % (
259+ self .http_call_result .status_code ,
260+ self .http_call_result .status_message ,
261+ self .reply .url ().toString (),
262+ )
263+ )
264+ headers = {
265+ str (h ): str (self .reply .rawHeader (h )) for h in self .reply .rawHeaderList ()
266+ }
234267 for k , v in headers .items ():
235268 self .msg_log ("%s: %s" % (k , v ))
236269 if len (self .http_call_result .text ) < 1024 :
@@ -255,17 +288,19 @@ def request(self, url, method="GET", body=None, headers=None, redirections=DEFAU
255288 raise self .exception_class (self .http_call_result .reason )
256289 return (self .http_call_result , self .http_call_result .text )
257290
258- #@pyqtSlot()
291+ # @pyqtSlot()
259292 def downloadProgress (self , bytesReceived , bytesTotal ):
260293 """Keep track of the download progress"""
261- #self.msg_log("downloadProgress %s of %s ..." % (bytesReceived, bytesTotal))
294+ # self.msg_log("downloadProgress %s of %s ..." % (bytesReceived, bytesTotal))
262295 pass
263296
264- #@pyqtSlot()
297+ # @pyqtSlot()
265298 def replyFinished (self ):
266299 err = self .reply .error ()
267300 httpStatus = self .reply .attribute (QNetworkRequest .HttpStatusCodeAttribute )
268- httpStatusMessage = self .reply .attribute (QNetworkRequest .HttpReasonPhraseAttribute )
301+ httpStatusMessage = self .reply .attribute (
302+ QNetworkRequest .HttpReasonPhraseAttribute
303+ )
269304 self .http_call_result .status_code = httpStatus
270305 self .http_call_result .status = httpStatus
271306 self .http_call_result .status_message = httpStatusMessage
@@ -274,7 +309,8 @@ def replyFinished(self):
274309 self .http_call_result .headers [str (k ).lower ()] = str (v )
275310 if err != QNetworkReply .NoError :
276311 msg = "Network error #{0}: {1}" .format (
277- self .reply .error (), self .reply .errorString ())
312+ self .reply .error (), self .reply .errorString ()
313+ )
278314 self .http_call_result .reason = msg
279315 self .http_call_result .ok = False
280316 self .msg_log (msg )
@@ -288,13 +324,13 @@ def replyFinished(self):
288324 # since Python 3 readAll() returns a PyQt5.QByteArray, we
289325 # want only the data
290326 if PYTHON_VERSION >= 3 :
291- self .http_call_result .text = self .reply .readAll ().data ().decode (' utf-8' )
327+ self .http_call_result .text = self .reply .readAll ().data ().decode (" utf-8" )
292328 else :
293329 self .http_call_result .text = str (self .reply .readAll ())
294330 self .http_call_result .ok = True
295331 self .reply .deleteLater ()
296332
297- #@pyqtSlot()
333+ # @pyqtSlot()
298334 def sslErrors (self , reply , ssl_errors ):
299335 """
300336 Handle SSL errors, logging them if debug is on and ignoring them
0 commit comments