Skip to content
Snippets Groups Projects

HTTP télécharger du texte par Python/QGIS

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by DESBOEUFS Philippe

    Fonction simple pour télécharger sur une API du texte, du json, du xml... Si un proxy est défini dans QGIS, la requête passera automatiquement par ce proxy.

    Edited
    http_telecharger_texte_Python_QGIS.py 1.71 KiB
    from qgis.PyQt.QtCore import *
    from qgis.PyQt.QtNetwork import QNetworkRequest, QNetworkReply
    from qgis.core import QgsNetworkAccessManager
    
    def telecharger_texte(url, params={}, headers={}):
    	qurl = QUrl(url)
    	# Facultatif, pour ajouter des paramètres à la requête :
    	q = QUrlQuery(qurl)
    	for key, value in params.items():  q.addQueryItem(key, value)
    	qurl.setQuery(q)
    	request = QNetworkRequest(qurl)
    	# Option pour forcer la requete par le réseau et ne pas utiliser le cache :
    	# request.setAttribute(QNetworkRequest.CacheLoadControlAttribute,QNetworkRequest.AlwaysNetwork)
    	
    	# Infos header optionnelles :
    	for key, value in headers.items():  request.setRawHeader(key, value)
    	
    	reply = QgsNetworkAccessManager.instance().get(request)
    	evloop= QEventLoop()
    	reply.finished.connect(evloop.quit)
    	evloop.exec_(QEventLoop.AllEvents) 
    	reply.deleteLater()
    	
    	error = reply.error()
    	if error == QNetworkReply.NoError: # OK
    		return reply.readAll().data().decode('utf-8','ignore')
    	elif error == QNetworkReply.SslHandshakeFailedError:
    		print('Certificat obsolete qui bloque la requete')
    		return False
    	if error == QNetworkReply.ConnectionRefusedError:
    		print('The remote server refused the connection (the server is not accepting requests)')
    		return False
    	if error == QNetworkReply.RemoteHostClosedError :
    		print('The remote server closed the connection prematurely before the entire reply was received and processed')
    		return False
    	if error == QNetworkReply.HostNotFoundError :
    		print('The remote host name was not found (invalid hostname)')
    		return False
    	else:
    		print('Autre erreur reseau :', str(error) )
    		return False
    
    
    texte = telecharger_texte('https://geo.api.gouv.fr/departements')
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment