本文整理汇总了Python中qgis.core.QgsAuthManager类的典型用法代码示例。如果您正苦于以下问题:Python QgsAuthManager类的具体用法?Python QgsAuthManager怎么用?Python QgsAuthManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QgsAuthManager类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: showLogin
def showLogin(self):
self.stackedWidget.setCurrentIndex(0)
self.webView.setVisible(False)
self.webView.setHtml("")
self.leSearch.setText("")
self.tabsContent.setCurrentIndex(0)
self.svgLogo.show()
self.lblSmallLogo.hide()
connect.resetToken()
self.token = None
fillCredentials = pluginSetting("rememberCredentials")
if fillCredentials:
self.connectWidget.setRemember(Qt.Checked)
username = ""
password = ""
if self.authId != "":
authConfig = QgsAuthMethodConfig()
if self.authId in QgsAuthManager.instance().configIds():
QgsAuthManager.instance().loadAuthenticationConfig(self.authId, authConfig, True)
username = authConfig.config("username")
password = authConfig.config("password")
self.connectWidget.setLogin(username)
self.connectWidget.setPassword(password)
else:
self.connectWidget.setRemember(Qt.Unchecked)
self.connectWidget.setLogin("")
self.connectWidget.setPassword("")
开发者ID:boundlessgeo,项目名称:qgis-connect-plugin,代码行数:29,代码来源:connectdockwidget.py
示例2: app_initialized
def app_initialized(self):
"""
Semi-automated pre-population with minimal user interaction, but only at
end of app launch, not after (like when loading via Plugin Manager).
"""
# noinspection PyArgumentList
if (not QgsAuthManager.instance().masterPasswordHashInDb()
or not QgsAuthManager.instance().getCertIdentities()):
authdlg = PopulateAuthSystemDialog(parent=self.mw,
qgis_iface=self.iface,
title=self.title,
init_run=True)
authdlg.exec_()
开发者ID:boundlessgeo,项目名称:qgis-populate-auth-system,代码行数:13,代码来源:populate_auth_system.py
示例3: __init__
def __init__(self, parent, plugin):
QDialog.__init__(self, parent)
self.setupUi(self)
self.plugin = plugin
self.mResult = ""
self.progressBar.setRange(0, 0)
self.progressBar.setFormat("%p%")
self.labelName.setText(plugin["name"])
self.buttonBox.clicked.connect(self.abort)
url = QUrl(plugin["download_url"])
fileName = plugin["filename"]
tmpDir = QDir.tempPath()
tmpPath = QDir.cleanPath(tmpDir + "/" + fileName)
self.file = QFile(tmpPath)
self.request = QNetworkRequest(url)
authcfg = repositories.all()[plugin["zip_repository"]]["authcfg"]
if authcfg and isinstance(authcfg, basestring):
if not QgsAuthManager.instance().updateNetworkRequest(
self.request, authcfg.strip()):
self.mResult = self.tr(
"Update of network request with authentication "
"credentials FAILED for configuration '{0}'").format(authcfg)
self.request = None
if self.request is not None:
self.reply = QgsNetworkAccessManager.instance().get(self.request)
self.reply.downloadProgress.connect(self.readProgress)
self.reply.finished.connect(self.requestFinished)
self.stateChanged(4)
开发者ID:Antoviscomi,项目名称:QGIS,代码行数:33,代码来源:qgsplugininstallerinstallingdialog.py
示例4: initAuthManager
def initAuthManager():
"""
Setup AuthManager instance.
heavily based on testqgsauthmanager.cpp.
"""
global AUTHM
if not AUTHM:
AUTHM = QgsAuthManager.instance()
# check if QgsAuthManager has been already initialised... a side effect
# of the QgsAuthManager.init() is that AuthDbPath is set
if AUTHM.authenticationDbPath():
# already initilised => we are inside QGIS. Assumed that the
# actual qgis_auth.db has the same master pwd as AUTHDB_MASTERPWD
if AUTHM.masterPasswordIsSet():
msg = 'Auth master password not set from passed string'
assert AUTHM.masterPasswordSame(AUTHDB_MASTERPWD)
else:
msg = 'Master password could not be set'
assert AUTHM.setMasterPassword(AUTHDB_MASTERPWD, True), msg
else:
# outside qgis => setup env var before db init
os.environ['QGIS_AUTH_DB_DIR_PATH'] = AUTHDBDIR
msg = 'Master password could not be set'
assert AUTHM.setMasterPassword(AUTHDB_MASTERPWD, True), msg
AUTHM.init(AUTHDBDIR)
开发者ID:MonsantoCo,项目名称:qgis-geoserver-plugin,代码行数:26,代码来源:utils.py
示例5: setUpClass
def setUpClass(cls):
cls.authm = QgsAuthManager.instance()
assert not cls.authm.isDisabled(), cls.authm.disabledMessage()
cls.mpass = 'pass' # master password
db1 = QFileInfo(cls.authm.authenticationDatabasePath()).canonicalFilePath()
db2 = QFileInfo(AUTHDBDIR + '/qgis-auth.db').canonicalFilePath()
msg = 'Auth db temp path does not match db path of manager'
assert db1 == db2, msg
开发者ID:ndavid,项目名称:QGIS,代码行数:10,代码来源:test_qgsauthsystem.py
示例6: showEvent
def showEvent(self, event):
fillCredentials = pluginSetting("rememberCredentials")
if self.authId != '' and fillCredentials and not self.loggedIn:
authConfig = QgsAuthMethodConfig()
if self.authId in QgsAuthManager.instance().configIds():
QgsAuthManager.instance().loadAuthenticationConfig(self.authId, authConfig, True)
username = authConfig.config('username')
password = authConfig.config('password')
else:
self.authId = ''
utils.setRepositoryAuth(self.authId)
self._showMessage('Could not find Connect credentials in the database.',
QgsMessageBar.WARNING)
username = ''
password = ''
self.connectWidget.setLogin(username)
self.connectWidget.setPassword(password)
BASE.showEvent(self, event)
开发者ID:boundlessgeo,项目名称:qgis-connect-plugin,代码行数:20,代码来源:connectdockwidget.py
示例7: setUpClass
def setUpClass(cls):
cls.authm = QgsAuthManager.instance()
cls.authdbdir = tempfile.mkdtemp()
cls.authm.init(cls.authdbdir)
msg = 'Auth db could not be created in temp dir'
assert os.path.exists(cls.authm.authenticationDbPath()), msg
db1 = QFileInfo(cls.authm.authenticationDbPath()).canonicalFilePath()
db2 = QFileInfo(cls.authdbdir + '/qgis-auth.db').canonicalFilePath()
msg = 'Auth db path does not match db path of manager'
assert db1 == db2, msg
开发者ID:dakcarto,项目名称:PopulateCredentials,代码行数:11,代码来源:test_qgsauthsystem_api-sample.py
示例8: testProxyIsUpdated
def testProxyIsUpdated(self):
"""
Test that proxy is updated
"""
authm = QgsAuthManager.instance()
nam = QgsNetworkAccessManager.instance()
proxy = nam.proxy()
self.assertEqual(proxy.password(), '')
self.assertEqual(proxy.user(), '')
self.assertTrue(authm.updateNetworkProxy(proxy, self.auth_config.id()))
self.assertEqual(proxy.user(), self.username)
self.assertEqual(proxy.password(), self.password)
开发者ID:giohappy,项目名称:QGIS,代码行数:12,代码来源:test_authmanager_proxy.py
示例9: setUpAuth
def setUpAuth(cls):
"""Run before all tests and set up authentication"""
authm = QgsAuthManager.instance()
assert authm.setMasterPassword("masterpassword", True)
cls.pg_conf = os.path.join(cls.tempfolder, "postgresql.conf")
cls.pg_hba = os.path.join(cls.tempfolder, "pg_hba.conf")
# Client side
cls.sslrootcert_path = os.path.join(cls.certsdata_path, "chains_subissuer-issuer-root_issuer2-root2.pem")
cls.sslcert = os.path.join(cls.certsdata_path, "gerardus_cert.pem")
cls.sslkey = os.path.join(cls.certsdata_path, "gerardus_key.pem")
assert os.path.isfile(cls.sslcert)
assert os.path.isfile(cls.sslkey)
assert os.path.isfile(cls.sslrootcert_path)
os.chmod(cls.sslcert, stat.S_IRUSR)
os.chmod(cls.sslkey, stat.S_IRUSR)
os.chmod(cls.sslrootcert_path, stat.S_IRUSR)
cls.auth_config = QgsAuthMethodConfig("PKI-Paths")
cls.auth_config.setConfig("certpath", cls.sslcert)
cls.auth_config.setConfig("keypath", cls.sslkey)
cls.auth_config.setName("test_pki_auth_config")
cls.username = "Gerardus"
cls.sslrootcert = QSslCertificate.fromPath(cls.sslrootcert_path)
assert cls.sslrootcert is not None
authm.storeCertAuthorities(cls.sslrootcert)
authm.rebuildCaCertsCache()
authm.rebuildTrustedCaCertsCache()
authm.rebuildCertTrustCache()
assert authm.storeAuthenticationConfig(cls.auth_config)[0]
assert cls.auth_config.isValid()
# Server side
cls.server_cert = os.path.join(cls.certsdata_path, "localhost_ssl_cert.pem")
cls.server_key = os.path.join(cls.certsdata_path, "localhost_ssl_key.pem")
cls.server_rootcert = cls.sslrootcert_path
os.chmod(cls.server_cert, stat.S_IRUSR)
os.chmod(cls.server_key, stat.S_IRUSR)
os.chmod(cls.server_rootcert, stat.S_IRUSR)
# Place conf in the data folder
with open(cls.pg_conf, "w+") as f:
f.write(
QGIS_POSTGRES_CONF_TEMPLATE
% {
"port": cls.port,
"tempfolder": cls.tempfolder,
"server_cert": cls.server_cert,
"server_key": cls.server_key,
"sslrootcert_path": cls.sslrootcert_path,
}
)
with open(cls.pg_hba, "w+") as f:
f.write(QGIS_POSTGRES_HBA_TEMPLATE)
开发者ID:kalxas,项目名称:QGIS,代码行数:53,代码来源:test_authmanager_pki_postgres.py
示例10: accept
def accept(self):
utils.addBoundlessRepository()
if self.leLogin.text() == '' or self.lePassword.text() == '':
QDialog.accept(self)
return
if self.authId == '':
authConfig = QgsAuthMethodConfig('Basic')
authId = QgsAuthManager.instance().uniqueConfigId()
authConfig.setId(authId)
authConfig.setConfig('username', self.leLogin.text())
authConfig.setConfig('password', self.lePassword.text())
authConfig.setName('Boundless Connect Portal')
settings = QSettings('Boundless', 'BoundlessConnect')
authConfig.setUri(settings.value('repoUrl', '', unicode))
if QgsAuthManager.instance().storeAuthenticationConfig(authConfig):
utils.setRepositoryAuth(authId)
else:
QMessageBox.information(self, self.tr('Error!'), self.tr('Unable to save credentials'))
else:
authConfig = QgsAuthMethodConfig()
QgsAuthManager.instance().loadAuthenticationConfig(self.authId, authConfig, True)
authConfig.setConfig('username', self.leLogin.text())
authConfig.setConfig('password', self.lePassword.text())
QgsAuthManager.instance().updateAuthenticationConfig(authConfig)
QDialog.accept(self)
开发者ID:elpaso,项目名称:qgis-connect-plugin,代码行数:29,代码来源:connectdialog.py
示例11: saveOrUpdateAuthId
def saveOrUpdateAuthId(self):
if self.authId == '':
authConfig = QgsAuthMethodConfig('Basic')
self.authId = QgsAuthManager.instance().uniqueConfigId()
authConfig.setId(self.authId)
authConfig.setConfig('username', self.connectWidget.login().strip())
authConfig.setConfig('password', self.connectWidget.password().strip())
authConfig.setName('Boundless Connect Portal')
authConfig.setUri(pluginSetting('repoUrl'))
if QgsAuthManager.instance().storeAuthenticationConfig(authConfig):
utils.setRepositoryAuth(self.authId)
else:
self._showMessage('Unable to save credentials.', QgsMessageBar.WARNING)
else:
authConfig = QgsAuthMethodConfig()
QgsAuthManager.instance().loadAuthenticationConfig(self.authId, authConfig, True)
authConfig.setConfig('username', self.connectWidget.login().strip())
authConfig.setConfig('password', self.connectWidget.password().strip())
QgsAuthManager.instance().updateAuthenticationConfig(authConfig)
# also setup OAuth2 configuration if possible
if oauth2_supported():
endpointUrl = "{}/token/oauth?version={}".format(pluginSetting("connectEndpoint"), pluginSetting("apiVersion"))
setup_oauth(self.connectWidget.login().strip(), self.connectWidget.password().strip(), endpointUrl)
开发者ID:boundlessgeo,项目名称:qgis-connect-plugin,代码行数:26,代码来源:connectdockwidget.py
示例12: fetch
def fetch(self):
"""Fetch the content."""
# Initialize some properties again
self._content = None
self._network_finished = False
self._network_timeout = False
request = QNetworkRequest(QUrl(self._url))
request.setAttribute(
QNetworkRequest.CacheLoadControlAttribute,
QNetworkRequest.AlwaysNetwork)
if self._auth_cfg and qgis_version() >= 21200:
LOGGER.info('Update request with auth_cfg %s' % self._auth_cfg)
QgsAuthManager.instance().updateNetworkRequest(
request, self._auth_cfg
)
self._reply = self._network_manager.get(request)
self._reply.finished.connect(self.fetch_finished)
self._network_manager.requestTimedOut.connect(self.request_timeout)
while not self._reply.isFinished():
# noinspection PyArgumentList
QCoreApplication.processEvents()
# Finished
description = None
if self._reply.error() != QNetworkReply.NoError:
status = False
description = self._reply.errorString()
else:
status = True
self._content = self._reply.readAll()
self._reply.deleteLater()
return status, description
开发者ID:akbargumbira,项目名称:qgis_resources_sharing,代码行数:38,代码来源:network_manager.py
示例13: setUpAuth
def setUpAuth(cls):
"""Run before all tests and set up authentication"""
authm = QgsAuthManager.instance()
assert (authm.setMasterPassword('masterpassword', True))
cls.pg_conf = os.path.join(cls.tempfolder, 'postgresql.conf')
cls.pg_hba = os.path.join(cls.tempfolder, 'pg_hba.conf')
# Client side
cls.sslrootcert_path = os.path.join(cls.certsdata_path, 'chains_subissuer-issuer-root_issuer2-root2.pem')
cls.sslcert = os.path.join(cls.certsdata_path, 'gerardus_cert.pem')
cls.sslkey = os.path.join(cls.certsdata_path, 'gerardus_key.pem')
assert os.path.isfile(cls.sslcert)
assert os.path.isfile(cls.sslkey)
assert os.path.isfile(cls.sslrootcert_path)
os.chmod(cls.sslcert, stat.S_IRUSR)
os.chmod(cls.sslkey, stat.S_IRUSR)
os.chmod(cls.sslrootcert_path, stat.S_IRUSR)
cls.auth_config = QgsAuthMethodConfig("PKI-Paths")
cls.auth_config.setConfig('certpath', cls.sslcert)
cls.auth_config.setConfig('keypath', cls.sslkey)
cls.auth_config.setName('test_pki_auth_config')
cls.username = 'Gerardus'
cls.sslrootcert = QSslCertificate.fromPath(cls.sslrootcert_path)
assert cls.sslrootcert is not None
authm.storeCertAuthorities(cls.sslrootcert)
authm.rebuildCaCertsCache()
authm.rebuildTrustedCaCertsCache()
authm.rebuildCertTrustCache()
assert (authm.storeAuthenticationConfig(cls.auth_config)[0])
assert cls.auth_config.isValid()
# Server side
cls.server_cert = os.path.join(cls.certsdata_path, 'localhost_ssl_cert.pem')
cls.server_key = os.path.join(cls.certsdata_path, 'localhost_ssl_key.pem')
cls.server_rootcert = cls.sslrootcert_path
os.chmod(cls.server_cert, stat.S_IRUSR)
os.chmod(cls.server_key, stat.S_IRUSR)
os.chmod(cls.server_rootcert, stat.S_IRUSR)
# Place conf in the data folder
with open(cls.pg_conf, 'w+') as f:
f.write(QGIS_POSTGRES_CONF_TEMPLATE % {
'port': cls.port,
'tempfolder': cls.tempfolder,
'server_cert': cls.server_cert,
'server_key': cls.server_key,
'sslrootcert_path': cls.sslrootcert_path,
})
with open(cls.pg_hba, 'w+') as f:
f.write(QGIS_POSTGRES_HBA_TEMPLATE)
开发者ID:wongjimsan,项目名称:QGIS,代码行数:50,代码来源:test_authmanager_pki_postgres.py
示例14: setUpClass
def setUpClass(cls):
"""Run before all tests:
Creates an auth configuration"""
# Enable auth
# os.environ['QGIS_AUTH_PASSWORD_FILE'] = QGIS_AUTH_PASSWORD_FILE
authm = QgsAuthManager.instance()
assert (authm.setMasterPassword('masterpassword', True))
cls.auth_config = QgsAuthMethodConfig('Basic')
cls.auth_config.setName('test_auth_config')
cls.username = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
cls.password = cls.username[::-1] # reversed
cls.auth_config.setConfig('username', cls.username)
cls.auth_config.setConfig('password', cls.password)
assert (authm.storeAuthenticationConfig(cls.auth_config)[0])
开发者ID:giohappy,项目名称:QGIS,代码行数:14,代码来源:test_authsettingswidget.py
示例15: __init__
def __init__(self, parent=None):
super(ConnectDialog, self).__init__(parent)
self.setupUi(self)
self.setWindowIcon(QIcon(os.path.join(pluginPath, 'icons', 'connect.svg')))
self.svgLogo.load(os.path.join(pluginPath, 'icons', 'connect-logo.svg'))
btnOk = self.buttonBox.button(QDialogButtonBox.Ok)
btnOk.setText(self.tr('Login'))
settings = QSettings()
settings.beginGroup(reposGroup)
self.authId = settings.value(boundlessRepoName + '/authcfg', '', unicode)
settings.endGroup()
if self.authId != '':
authConfig = QgsAuthMethodConfig()
QgsAuthManager.instance().loadAuthenticationConfig(self.authId, authConfig, True)
username = authConfig.config('username')
password = authConfig.config('password')
self.leLogin.setText(username)
self.lePassword.setText(password)
self.buttonBox.helpRequested.connect(self.showHelp)
开发者ID:elpaso,项目名称:qgis-connect-plugin,代码行数:24,代码来源:connectdialog.py
示例16: setUpClass
def setUpClass(cls):
"""Run before all tests:
Creates an auth configuration"""
cls.port = QGIS_SERVER_ENDPOINT_PORT
# Clean env just to be sure
env_vars = ['QUERY_STRING', 'QGIS_PROJECT_FILE']
for ev in env_vars:
try:
del os.environ[ev]
except KeyError:
pass
cls.testdata_path = unitTestDataPath('qgis_server') + '/'
cls.project_path = cls.testdata_path + "test_project.qgs"
# Enable auth
#os.environ['QGIS_AUTH_PASSWORD_FILE'] = QGIS_AUTH_PASSWORD_FILE
authm = QgsAuthManager.instance()
assert (authm.setMasterPassword('masterpassword', True))
cls.auth_config = QgsAuthMethodConfig('Basic')
cls.auth_config.setName('test_auth_config')
cls.username = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
cls.password = cls.username[::-1] # reversed
cls.auth_config.setConfig('username', cls.username)
cls.auth_config.setConfig('password', cls.password)
assert (authm.storeAuthenticationConfig(cls.auth_config)[0])
cls.hostname = '127.0.0.1'
cls.protocol = 'http'
os.environ['QGIS_SERVER_HTTP_BASIC_AUTH'] = '1'
os.environ['QGIS_SERVER_USERNAME'] = cls.username
os.environ['QGIS_SERVER_PASSWORD'] = cls.password
os.environ['QGIS_SERVER_PORT'] = str(cls.port)
os.environ['QGIS_SERVER_HOST'] = cls.hostname
server_path = os.path.dirname(os.path.realpath(__file__)) + \
'/qgis_wrapped_server.py'
cls.server = subprocess.Popen([sys.executable, server_path],
env=os.environ, stdout=subprocess.PIPE)
line = cls.server.stdout.readline()
cls.port = int(re.findall(b':(\d+)', line)[0])
assert cls.port != 0
# Wait for the server process to start
assert waitServer('%s://%s:%s' % (cls.protocol, cls.hostname, cls.port)), "Server is not responding! %s://%s:%s" % (cls.protocol, cls.hostname, cls.port)
开发者ID:drnextgis,项目名称:QGIS,代码行数:43,代码来源:test_authmanager_password_ows.py
示例17: requestFetching
def requestFetching(self, key):
""" start fetching the repository given by key """
self.mRepositories[key]["state"] = 1
url = QUrl(self.mRepositories[key]["url"] + self.urlParams())
# v=str(QGis.QGIS_VERSION_INT)
# url.addQueryItem('qgis', '.'.join([str(int(s)) for s in [v[0], v[1:3]]]) ) # don't include the bugfix version!
self.mRepositories[key]["QRequest"] = QNetworkRequest(url)
authcfg = self.mRepositories[key]["authcfg"]
if authcfg and isinstance(authcfg, basestring):
if not QgsAuthManager.instance().updateNetworkRequest(self.mRepositories[key]["QRequest"], authcfg.strip()):
msg = QCoreApplication.translate(
"QgsPluginInstaller",
"Update of network request with authentication " "credentials FAILED for configuration '{0}'",
).format(authcfg)
iface.pluginManagerInterface().pushMessage(msg, QgsMessageBar.WARNING)
self.mRepositories[key]["QRequest"] = None
return
self.mRepositories[key]["QRequest"].setAttribute(QNetworkRequest.User, key)
self.mRepositories[key]["xmlData"] = QgsNetworkAccessManager.instance().get(self.mRepositories[key]["QRequest"])
self.mRepositories[key]["xmlData"].setProperty("reposName", key)
self.mRepositories[key]["xmlData"].downloadProgress.connect(self.mRepositories[key]["Relay"].dataReadProgress)
self.mRepositories[key]["xmlData"].finished.connect(self.xmlDownloaded)
开发者ID:blazek,项目名称:QGIS,代码行数:23,代码来源:installer_data.py
示例18: QSettings
# only once on a fresh QGIS installation before the user
# started QGIS for the first time.
from qgis.PyQt.QtCore import QSettings
from qgis.core import QgsAuthManager, QgsAuthMethodConfig, QgsMessageLog, Qgis
AUTHDB_MASTERPWD = 'password'
QgsMessageLog.logMessage("Init script: %s" % __file__, tag="Init script", level=Qgis.Info)
# Do not run twice!
if not QSettings().value("InitScript/AuthCfgCreated", type=bool):
QSettings().setValue("InitScript/AuthCfgCreated", True)
# Check if authdb master password is set
am = QgsAuthManager.instance()
if not am.masterPasswordHashInDb():
# Set it!
am.setMasterPassword(AUTHDB_MASTERPWD, True)
# Create config
am.authenticationDbPath()
am.masterPasswordIsSet()
cfg = QgsAuthMethodConfig()
cfg.setId('myauth1') # Optional, useful for plugins to retrieve an authcfg
cfg.setName('Example Auth Config HTTP Basic')
cfg.setMethod('Basic')
cfg.setConfig('username', 'username')
cfg.setConfig('password', 'password')
am.storeAuthenticationConfig(cfg)
else:
QgsMessageLog.logMessage("Master password was already set: aborting", tag="Init script", level=Qgis.Info)
开发者ID:boundlessgeo,项目名称:desktop-documentation,代码行数:31,代码来源:006_add_authcfg.py
示例19: request
def request(self, url, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None):
"""
Make a network request by calling QgsNetworkAccessManager.
redirections argument is ignored and is here only for httplib2 compatibility.
"""
self.msg_log(u'http_call request: {0}'.format(url))
self.http_call_result = Response({
'status': 0,
'status_code': 0,
'status_message': '',
'text' : '',
'ok': False,
'headers': {},
'reason': '',
'exception': None,
})
req = QNetworkRequest()
req.setUrl(QUrl(url))
if headers is not None:
# This fixes a wierd error with compressed content not being correctly
# inflated.
# If you set the header on the QNetworkRequest you are basically telling
# QNetworkAccessManager "I know what I'm doing, please don't do any content
# encoding processing".
# See: https://bugs.webkit.org/show_bug.cgi?id=63696#c1
try:
del headers['Accept-Encoding']
except KeyError:
pass
for k, v in headers.items():
self.msg_log("Setting header %s to %s" % (k, v))
req.setRawHeader(k, v)
if self.authid:
self.msg_log("Update request w/ authid: {0}".format(self.authid))
QgsAuthManager.instance().updateNetworkRequest(req, self.authid)
if self.reply is not None and self.reply.isRunning():
self.reply.close()
if method.lower() == 'delete':
func = getattr(QgsNetworkAccessManager.instance(), 'deleteResource')
else:
func = getattr(QgsNetworkAccessManager.instance(), method.lower())
# Calling the server ...
# Let's log the whole call for debugging purposes:
self.msg_log("Sending %s request to %s" % (method.upper(), req.url().toString()))
headers = {str(h): str(req.rawHeader(h)) for h in req.rawHeaderList()}
for k, v in headers.items():
self.msg_log("%s: %s" % (k, v))
if method.lower() in ['post', 'put']:
if isinstance(body, file):
body = body.read()
self.reply = func(req, body)
else:
self.reply = func(req)
if self.authid:
self.msg_log("Update reply w/ authid: {0}".format(self.authid))
QgsAuthManager.instance().updateNetworkReply(self.reply, self.authid)
self.reply.sslErrors.connect(self.sslErrors)
self.reply.finished.connect(self.replyFinished)
# Call and block
self.el = QEventLoop()
self.reply.finished.connect(self.el.quit)
self.reply.downloadProgress.connect(self.downloadProgress)
# Catch all exceptions (and clean up requests)
try:
self.el.exec_()
# Let's log the whole response for debugging purposes:
self.msg_log("Got response %s %s from %s" % \
(self.http_call_result.status_code,
self.http_call_result.status_message,
self.reply.url().toString()))
headers = {str(h): str(self.reply.rawHeader(h)) for h in self.reply.rawHeaderList()}
for k, v in headers.items():
self.msg_log("%s: %s" % (k, v))
if len(self.http_call_result.text) < 1024:
self.msg_log("Payload :\n%s" % self.http_call_result.text)
else:
self.msg_log("Payload is > 1 KB ...")
except Exception, e:
raise e
开发者ID:MonsantoCo,项目名称:qgis-geoserver-plugin,代码行数:82,代码来源:networkaccessmanager.py
示例20: __init__
def __init__(self, parent=None, visible=False):
super(ConnectDockWidget, self).__init__(parent)
self.setupUi(self)
self.loggedIn = False
self.token = None
self.progressBar.hide()
self.setVisible(visible)
self.setWindowIcon(QIcon(os.path.join(pluginPath, 'icons', 'connect.svg')))
self.svgLogo.load(os.path.join(pluginPath, 'icons', 'connect-logo.svg'))
self.lblSmallLogo.setPixmap(QPixmap(os.path.join(pluginPath, 'icons', 'connect.png')))
self.lblSmallLogo.hide()
btnOk = self.buttonBox.button(QDialogButtonBox.Ok)
btnOk.setText('Login')
# setup tab bar
self.tabsContent.addTab('Knowledge')
self.tabsContent.addTab('Data')
self.tabsContent.addTab('Plugins')
self.tabsContent.setDocumentMode(True)
self.tabsContent.setDrawBase(False)
self._toggleCategoriesSelector(True)
self.tabsContent.setCurrentIndex(0)
self.tabsContent.currentChanged.connect(self.tabChanged)
self.buttonBox.helpRequested.connect(self.showHelp)
self.buttonBox.accepted.connect(self.logIn)
self.btnSignOut.clicked.connect(self.showLogin)
self.labelLevel.linkActivated.connect(self.showLogin)
self.leSearch.buttonClicked.connect(self.search)
self.leSearch.returnPressed.connect(self.search)
self.connectWidget.rememberStateChanged.connect(self.updateSettings)
self.webView.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
cssFile = os.path.join(pluginPath, "resources", "search.css")
with open(cssFile) as f:
content = f.read()
self.css = content.replace("#PLUGIN_PATH#", QUrl.fromLocalFile(pluginPath).toString())
self.webView.linkClicked.connect(self.linkClicked)
for cat, cls in connect.categories.items():
self.cmbContentType.addItem(cls[1], cat)
settings = QSettings()
settings.beginGroup(reposGroup)
self.authId = settings.value(boundlessRepoName + '/authcfg', '')
settings.endGroup()
if self.authId not in QgsAuthManager.instance().configIds():
self.authId = ''
utils.setRepositoryAuth(self.authId)
self._toggleSearchControls(True)
self.showLogin()
开发者ID:boundlessgeo,项目名称:qgis-connect-plugin,代码行数:61,代码来源:connectdockwidget.py
注:本文中的qgis.core.QgsAuthManager类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论