在qgis插件中设置代理参数。如何

时间:2014-04-13 09:30:27

标签: python plugins pyqt qgis

对于那些感兴趣的人,我发现了以用户透明的方式在qgis插件中设置代理设置的明确方法。如果您计划将webservices与urllib或QwebWiew一起使用,这将非常有用。 使用Qsetting函数可以从qgis应用程序读取和写入存储在注册表中的用户应用程序选项设置。问题是注册表密钥的使用没有记录,但是挖掘到qgis源代码可以找到它们并在插件中用于其他purpouse。 以下是正确设置代理参数的代码块。

    # procedure to set proxy if needed
    s = QSettings() #getting proxy from qgis options settings
    proxyEnabled = s.value("proxy/proxyEnabled", "")
    proxyType = s.value("proxy/proxyType", "" )
    proxyHost = s.value("proxy/proxyHost", "" )
    proxyPort = s.value("proxy/proxyPort", "" )
    proxyUser = s.value("proxy/proxyUser", "" )
    proxyPassword = s.value("proxy/proxyPassword", "" )
    if proxyEnabled == "true": # test if there are proxy settings
       proxy = QNetworkProxy()
       if proxyType == "DefaultProxy":
           proxy.setType(QNetworkProxy.DefaultProxy)
       elif proxyType == "Socks5Proxy":
           proxy.setType(QNetworkProxy.Socks5Proxy)
       elif proxyType == "HttpProxy":
           proxy.setType(QNetworkProxy.HttpProxy)
       elif proxyType == "HttpCachingProxy":
           proxy.setType(QNetworkProxy.HttpCachingProxy)
       elif proxyType == "FtpCachingProxy":
           proxy.setType(QNetworkProxy.FtpCachingProxy)
       proxy.setHostName(proxyHost)
       proxy.setPort(int(proxyPort))
       proxy.setUser(proxyUser)
       proxy.setPassword(proxyPassword)
       QNetworkProxy.setApplicationProxy(proxy)

2 个答案:

答案 0 :(得分:2)

要完成@gustry的答案,您必须从以下代码开始:

from PyQt4.QtCore import QUrl
from PyQt4.QtNetwork import QNetworkRequest
from qgis.core import QgsNetworkAccessManager

url = 'http://qgis.org/en/site/'

def urlCallFinished(reply):
    print(reply.readAll())
    reply.deleteLater()

networkAccessManager = QgsNetworkAccessManager.instance()
networkAccessManager.finished.connect(urlCallFinished)

req = QNetworkRequest(QUrl(url))
reply = networkAccessManager.get(req)

对于代理部分,QgsNetworkAccessManager可以使用the documentation所述的QNetworkProxy,QGIS已经为您管理;)。

答案 1 :(得分:1)

您应该使用QGIS提供的QgsNetworkAccessManager。 代理会自动为您设置。

from qgis.core import QgsNetworkAccessManager
network_manager = QgsNetworkAccessManager.instance()

http://qgis.org/api/classQgsNetworkAccessManager.html