本文整理汇总了Python中PyQt4.QtNetwork.QNetworkRequest.setRawHeader方法的典型用法代码示例。如果您正苦于以下问题:Python QNetworkRequest.setRawHeader方法的具体用法?Python QNetworkRequest.setRawHeader怎么用?Python QNetworkRequest.setRawHeader使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtNetwork.QNetworkRequest
的用法示例。
在下文中一共展示了QNetworkRequest.setRawHeader方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_request
# 需要导入模块: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkRequest import setRawHeader [as 别名]
def make_request(self, url):
url = QUrl(url)
req = QNetworkRequest(url)
for header in self.headers:
val = self.headers[header]
req.setRawHeader(header, val)
return req
示例2: doRequest
# 需要导入模块: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkRequest import setRawHeader [as 别名]
def doRequest(self, url, baseurl=None, wait_time=None, viewport=None, js_source=None, js_profile=None, console=False):
self.url = url
self.wait_time = defaults.WAIT_TIME if wait_time is None else wait_time
self.js_source = js_source
self.js_profile = js_profile
self.console = console
self.viewport = defaults.VIEWPORT if viewport is None else viewport
request = QNetworkRequest()
request.setUrl(QUrl(url))
if self.viewport != 'full':
# viewport='full' can't be set if content is not loaded yet
self._setViewportSize(self.viewport)
if baseurl:
self._baseUrl = QUrl(baseurl)
request.setOriginatingObject(self.web_page.mainFrame())
self._reply = self.network_manager.get(request)
self._reply.finished.connect(self._requestFinished)
else:
self.web_page.loadFinished.connect(self._loadFinished)
if self.splash_request.method == 'POST':
headers = self.splash_request.getAllHeaders()
for header_name, header_value in headers.items():
request.setRawHeader(header_name, header_value)
self.web_page.mainFrame().load(request,
QNetworkAccessManager.PostOperation,
self.splash_request.content.getvalue())
else:
self.web_page.mainFrame().load(request)
示例3: read
# 需要导入模块: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkRequest import setRawHeader [as 别名]
def read(self, **kwargs):
self.connect(self.manager, SIGNAL("finished( QNetworkReply* )"), self.readRequestFinished)
params = []
try:
queryable = kwargs["queryable"]
params.append({"queryable": queryable})
queryableList = QString(queryable).split(",")
except KeyError:
pass
for key, value in kwargs.items():
if QString(key).split("__")[0] in queryableList:
params.append({key: value})
url = "%s/stakeholders?" % self.host
for p in params:
url = "%s%s=%s&" % (url, p.keys()[0], p.values()[0])
qUrl = QUrl(url)
# Create a new request
request = QNetworkRequest(qUrl)
request.setRawHeader("Authorization", self.login)
request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
self.manager.get(request)
return url
示例4: open
# 需要导入模块: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkRequest import setRawHeader [as 别名]
def open(self, address, method='get', headers={}, auth=None, body=None):
"""Opens a web page.
:param address: The resource URL.
:param method: The Http method.
:param headers: An optional dict of extra request hearders.
:param auth: An optional tupple of HTTP auth (username, password).
:param body: An optional string containing a payload.
:return: Page resource, All loaded resources.
"""
body = body or QByteArray()
try:
method = getattr(QNetworkAccessManager,
"%sOperation" % method.capitalize())
except AttributeError:
raise Exception("Invalid http method %s" % method)
request = QNetworkRequest(QUrl(address))
request.CacheLoadControl(0)
for header in headers:
request.setRawHeader(header, headers[header])
self._auth = auth
self._auth_attempt = 0 # Avoids reccursion
self.main_frame.load(request, method, body)
self.loaded = False
return self.wait_for_page_loaded()
示例5: open
# 需要导入模块: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkRequest import setRawHeader [as 别名]
def open(self, address, method='get', headers={}, auth=None, body=None,
default_popup_response=None):
"""Opens a web page.
:param address: The resource URL.
:param method: The Http method.
:param headers: An optional dict of extra request hearders.
:param auth: An optional tuple of HTTP auth (username, password).
:param body: An optional string containing a payload.
:param default_popup_response: the default response for any confirm/
alert/prompt popup from the Javascript (replaces the need for the with
blocks)
:return: Page resource, All loaded resources.
"""
body = body or QByteArray()
try:
method = getattr(QNetworkAccessManager,
"%sOperation" % method.capitalize())
except AttributeError:
raise Error("Invalid http method %s" % method)
request = QNetworkRequest(QUrl(address))
request.CacheLoadControl(0)
for header in headers:
request.setRawHeader(header, headers[header])
self._auth = auth
self._auth_attempt = 0 # Avoids reccursion
self.main_frame.load(request, method, body)
self.loaded = False
Ghost._prompt_expected = (default_popup_response, None)
Ghost._confirm_expected = (default_popup_response, None)
return self.wait_for_page_loaded()
示例6: request
# 需要导入模块: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkRequest import setRawHeader [as 别名]
def request(self, iri, method="GET", extra_headers=None,
oauth_credentials=None, post_content=None):
"""Return a deferred that will be fired with a Response object."""
uri = self.iri_to_uri(iri)
request = QNetworkRequest(QUrl(uri))
request.setSslConfiguration(self.ssl_config)
headers = yield self.build_request_headers(uri, method, extra_headers,
oauth_credentials)
for key, value in headers.items():
request.setRawHeader(key, value)
post_buffer = QBuffer()
post_buffer.setData(post_content)
try:
result = yield self._perform_request(request, method, post_buffer)
except ProxyUnauthorizedError as e:
app_proxy = QNetworkProxy.applicationProxy()
proxy_host = app_proxy.hostName() if app_proxy else "proxy server"
got_creds = yield self.request_proxy_auth_credentials(
proxy_host, self.proxy_retry)
if got_creds:
self.proxy_retry = True
result = yield self.request(iri, method, extra_headers,
oauth_credentials, post_content)
else:
excp = WebClientError('Proxy creds needed.', e)
defer.returnValue(excp)
defer.returnValue(result)
示例7: query
# 需要导入模块: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkRequest import setRawHeader [as 别名]
def query(self, query):
"""
Perform a nominatim query
@param query: Query to execute
@type query: str
@raise NetWorkErrorException
@return: the result of the query
@rtype: str
"""
url_query = QUrl(self.__url)
query = QUrl.toPercentEncoding(query)
url_query.addEncodedQueryItem('q', query)
url_query.addQueryItem('info', 'QgisQuickOSMPlugin')
url_query.setPort(80)
proxy = get_proxy()
if proxy:
self.network.setProxy(proxy)
request = QNetworkRequest(url_query)
request.setRawHeader("User-Agent", "QuickOSM")
self.network_reply = self.network.get(request)
self.loop = QEventLoop()
self.network.finished.connect(self._end_of_request)
self.loop.exec_()
if self.network_reply.error() == QNetworkReply.NoError:
return json.loads(self.data)
else:
raise NetWorkErrorException(suffix="Nominatim API")
示例8: open
# 需要导入模块: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkRequest import setRawHeader [as 别名]
def open(self, address, method='get', headers={}, auth=None):
"""Opens a web page.
:param address: The resource URL.
:param method: The Http method.
:param headers: An optional dict of extra request hearders.
:param auth: An optional tupple of HTTP auth (Basic, username, password).
:return: Page resource, All loaded resources.
"""
body = QByteArray()
try:
method = getattr(QNetworkAccessManager,
"%sOperation" % method.capitalize())
except AttributeError:
raise Exception("Invalid http method %s" % method)
request = QNetworkRequest(QUrl(address))
if auth is not None:
auth_type, username, password = auth
def authenticate(reply, authenticator):
authenticator.setUser(username)
authenticator.setPassword(password)
self.page.networkAccessManager().authenticationRequired.connect(authenticate)
if not "User-Agent" in headers:
headers["User-Agent"] = self.user_agent
for header in headers:
request.setRawHeader(header, headers[header])
self.main_frame.load(request, method, body)
self.loaded = False
return self.wait_for_page_loaded()
示例9: createRequest
# 需要导入模块: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkRequest import setRawHeader [as 别名]
def createRequest(self, operation, request, outgoingData=None):
request = QNetworkRequest(request)
old_proxy = self.proxy()
# Hack to change Language
request.setRawHeader("Accept-Language","fr-FR,fr;q=0.8");
#request.setRawHeader("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
#request.setRawHeader("Connection","keep-alive");
splash_proxy_factory = self._getSplashProxyFactory(request)
if splash_proxy_factory:
proxy_query = QNetworkProxyQuery(request.url())
proxy = splash_proxy_factory.queryProxy(proxy_query)[0]
self.setProxy(proxy)
# this method is called createRequest, but in fact it creates a reply
reply = super(ProxiedQNetworkAccessManager, self).createRequest(
operation, request, outgoingData
)
reply.error.connect(self._handleError)
reply.finished.connect(self._handleFinished)
reply.metaDataChanged.connect(self._handleMetaData)
reply.downloadProgress.connect(self._handleDownloadProgress)
self.setProxy(old_proxy)
return reply
示例10: __page_load_slot
# 需要导入模块: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkRequest import setRawHeader [as 别名]
def __page_load_slot(self):
with self.__page_load_condition:
request = self.__page_load_request
# setea la operación
if request.method == 'GET':
operation = QNetworkAccessManager.GetOperation
elif request.method == 'POST':
operation = QNetworkAccessManager.PostOperation
else:
raise ValueError("Unsupported method %s" % request.method)
user_agent = None # el user agent para el request
# Si se definieron headers personalizados se setean tambien
qnetworkrequest =QNetworkRequest(UrlHelper.from_user_input(request.url))
for header, value in list(self.__custom_headers.items()):
qnetworkrequest.setRawHeader(header, value)
if header.lower() == 'user-agent':
user_agent = value
# setea url y headers
qnetworkrequest =QNetworkRequest(UrlHelper.from_user_input(request.url))
for header, value in list(request.headers.items()):
qnetworkrequest.setRawHeader(header, value)
if header.lower() == 'user-agent':
user_agent = value
self.__page._set_user_agent(user_agent)
# lo más importante: carga la página
self.__web_view.load(qnetworkrequest, operation, request.body)
示例11: doRequest
# 需要导入模块: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkRequest import setRawHeader [as 别名]
def doRequest(self, url, baseurl=None, wait_time=None, viewport=None,
js_source=None, js_profile=None, images=None, console=False):
self.url = url
self.wait_time = defaults.WAIT_TIME if wait_time is None else wait_time
self.js_source = js_source
self.js_profile = js_profile
self.console = console
self.viewport = defaults.VIEWPORT if viewport is None else viewport
self.web_page.settings().setAttribute(QWebSettings.AutoLoadImages, images)
# setup logging
if self.verbosity >= 4:
self.web_page.loadStarted.connect(self._loadStarted)
self.web_page.mainFrame().loadFinished.connect(self._frameLoadFinished)
self.web_page.mainFrame().loadStarted.connect(self._frameLoadStarted)
self.web_page.mainFrame().contentsSizeChanged.connect(self._contentsSizeChanged)
if self.verbosity >= 3:
self.web_page.mainFrame().javaScriptWindowObjectCleared.connect(self._javaScriptWindowObjectCleared)
self.web_page.mainFrame().initialLayoutCompleted.connect(self._initialLayoutCompleted)
self.web_page.mainFrame().urlChanged.connect(self._urlChanged)
# do the request
request = QNetworkRequest()
request.setUrl(QUrl(url.decode('utf8')))
if self.viewport != 'full':
# viewport='full' can't be set if content is not loaded yet
self._setViewportSize(self.viewport)
if getattr(self.splash_request, 'pass_headers', False):
headers = self.splash_request.getAllHeaders()
for name, value in headers.items():
request.setRawHeader(name, value)
if name.lower() == 'user-agent':
self.web_page.custom_user_agent = value
if baseurl:
# If baseurl is used, we download the page manually,
# then set its contents to the QWebPage and let it
# download related resources and render the result.
self._baseUrl = QUrl(baseurl.decode('utf8'))
request.setOriginatingObject(self.web_page.mainFrame())
self._reply = self.network_manager.get(request)
self._reply.finished.connect(self._requestFinished)
else:
self.web_page.loadFinished.connect(self._loadFinished)
if self.splash_request.method == 'POST':
body = self.splash_request.content.getvalue()
self.web_page.mainFrame().load(
request, QNetworkAccessManager.PostOperation, body
)
else:
self.web_page.mainFrame().load(request)
示例12: prepare_request
# 需要导入模块: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkRequest import setRawHeader [as 别名]
def prepare_request(self, url_string):
url = QUrl(url_string)
request = QNetworkRequest()
request.setUrl(url)
request.setRawHeader('User-Agent', 'Cuivre Web Browser')
return request
示例13: get
# 需要导入模块: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkRequest import setRawHeader [as 别名]
def get(self, url):
future = Future()
url = url = QUrl(url)
request = QNetworkRequest(url)
request.setRawHeader("User-Agent", "OWImageViewer/1.0")
request.setAttribute(
QNetworkRequest.CacheLoadControlAttribute,
QNetworkRequest.PreferCache
)
# Future yielding a QNetworkReply when finished.
reply = self._netmanager.get(request)
future._reply = reply
n_redir = 0
def on_reply_ready(reply, future):
nonlocal n_redir
if reply.error() == QNetworkReply.OperationCanceledError:
# The network request itself was canceled
future.cancel()
return
if reply.error() != QNetworkReply.NoError:
# XXX Maybe convert the error into standard
# http and urllib exceptions.
future.set_exception(Exception(reply.errorString()))
return
# Handle a possible redirection
location = reply.attribute(
QNetworkRequest.RedirectionTargetAttribute)
if location is not None and n_redir < 1:
n_redir += 1
print(location)
location = reply.url().resolved(location)
# Retry the original request with a new url.
request = QNetworkRequest(reply.request())
request.setUrl(location)
newreply = self._netmanager.get(request)
future._reply = newreply
newreply.finished.connect(
partial(on_reply_ready, newreply, future))
return
reader = QImageReader(reply)
image = reader.read()
if image.isNull():
future.set_exception(Exception(reader.errorString()))
else:
future.set_result(image)
reply.finished.connect(partial(on_reply_ready, reply, future))
return future
示例14: sendVote
# 需要导入模块: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkRequest import setRawHeader [as 别名]
def sendVote(self, plugin_id, vote):
""" send vote via the RPC """
if not plugin_id or not vote:
return False
url = "http://plugins.qgis.org/plugins/RPC2/"
params = "{\"id\":\"djangorpc\",\"method\":\"plugin.vote\",\"params\":[%s,%s]}" % (str(plugin_id), str(vote))
req = QNetworkRequest(QUrl(url))
req.setRawHeader("Content-Type", "application/json")
QgsNetworkAccessManager.instance().post(req, params)
return True
示例15: executeRequest
# 需要导入模块: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkRequest import setRawHeader [as 别名]
def executeRequest (self, url, callback, post = None):
self.messageBar.clearWidgets()
self.cmbOfferings.setEnabled (False)
self.tabWidget.setEnabled (False)
if post:
request = QNetworkRequest(url)
request.setRawHeader('Content-Type', 'application/xml')
self.reply = QgsNetworkAccessManager.instance().post(request,post)
else:
self.reply = QgsNetworkAccessManager.instance().get(QNetworkRequest(url))
progressMessageBar = self.messageBar.createMessage(self.tr("Please wait while downloading"))
progressBar = QtGui.QProgressBar(self)
progressBar.setMinimum(0)
progressBar.setFormat(self.tr("%v bytes downloaded!"))
progressBar.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
def updateProgress (read, total):
try:
progressBar.setMaximum (total)
progressBar.setValue (read)
except: pass
updateProgress (0,0)
self.reply.downloadProgress.connect (updateProgress)
progressMessageBar.layout().addWidget(progressBar)
btnAbort = QtGui.QPushButton(self.tr("Abort"))
btnAbort.clicked.connect(self.reply.abort)
progressMessageBar.layout().addWidget(btnAbort)
fd, replyFilename = mkstemp(suffix=".xml", prefix = callback.__name__, dir = self.selectedWorkDir())
os.close(fd)
replyFile = open (replyFilename, "w")
def replyReadyRead ():
try: replyFile.write (self.reply.readAll())
except: pass
self.reply.readyRead.connect(replyReadyRead)
def finishRequest ():
replyFile.close()
self.cmbOfferings.setEnabled (True)
self.tabWidget.setEnabled(True)
self.messageBar.clearWidgets()
if self.reply.error() != QNetworkReply.NoError:
self.messageBar.pushMessage(self.reply.errorString(), QgsMessageBar.CRITICAL)
else:
callback(replyFilename)
self.reply.deleteLater()
self.reply.finished.connect(finishRequest)
self.messageBar.pushWidget(progressMessageBar, QgsMessageBar.INFO)