本文整理汇总了Python中PyQt4.QtNetwork.QNetworkRequest类的典型用法代码示例。如果您正苦于以下问题:Python QNetworkRequest类的具体用法?Python QNetworkRequest怎么用?Python QNetworkRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QNetworkRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_request
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: _wrap_request
def _wrap_request(self, request):
req = QNetworkRequest(request)
req_id = next(self._request_ids)
req.setAttribute(self._REQUEST_ID, req_id)
if hasattr(request, 'timeout'):
req.timeout = request.timeout
return req, req_id
示例3: _doUpload
def _doUpload(self):
if self.current_track is None or self._aborted:
return
track, track_type = self.current_track
self.statusMessage.emit('Uploading {0}'.format(track['name']))
log.debug('Sending upload request (%s)', track['name'])
# data_fields, data = bryton_gpx_to_strava_json(track['gpx'])
data = tcx.bryton_gpx_to_tcx(track['gpx'], activity_type=track_type, pretty=False, device=self.device_info)
req = QNetworkRequest(QUrl(self.UPLOAD))
req.setHeader(QNetworkRequest.ContentTypeHeader,
"application/json")
# d2 = json.loads(open('tmp/test.json').read())
# d2['token'] = self.auth_token
# self.reply = self.network_manager.post(req, json.dumps(d2))
self.reply = self.network_manager.post(req, json.dumps({
'token' : self.auth_token,
'type' : 'tcx',
'data' : data,
'activity_type' : track_type,
}))
self.reply.finished.connect(self._onUploaded)
示例4: open
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: read
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
示例6: __downloadFile
def __downloadFile(self, url, filename, doneMethod = None):
"""
Private slot to download the given file.
@param url URL for the download (string or QString)
@param filename local name of the file (string or QString)
@param doneMethod method to be called when done
"""
self.__updateButton.setEnabled(False)
self.__downloadButton.setEnabled(False)
self.__downloadCancelButton.setEnabled(True)
self.statusLabel.setText(url)
self.__doneMethod = doneMethod
self.__downloadURL = url
self.__downloadFileName = QString(filename)
self.__downloadIODevice = QFile(self.__downloadFileName + ".tmp")
self.__downloadCancelled = False
request = QNetworkRequest(QUrl(url))
request.setAttribute(QNetworkRequest.CacheLoadControlAttribute,
QNetworkRequest.AlwaysNetwork)
reply = self.__networkManager.get(request)
self.connect(reply, SIGNAL("finished()"), self.__downloadFileDone)
self.connect(reply, SIGNAL("downloadProgress(qint64, qint64)"),
self.__downloadProgress)
self.__replies.append(reply)
示例7: request
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)
示例8: open
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: open
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()
示例10: query
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")
示例11: createRequest
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
示例12: __init__
def __init__(self, url, baseurl=None):
self.url = url
self.web_view = QWebView()
self.network_manager = SplashQNetworkAccessManager()
self.web_page = SplashQWebPage()
self.web_page.setNetworkAccessManager(self.network_manager)
self.web_view.setPage(self.web_page)
self.web_view.setAttribute(Qt.WA_DeleteOnClose, True)
settings = self.web_view.settings()
settings.setAttribute(QWebSettings.JavascriptEnabled, True)
settings.setAttribute(QWebSettings.PluginsEnabled, False)
settings.setAttribute(QWebSettings.PrivateBrowsingEnabled, True)
settings.setAttribute(QWebSettings.LocalStorageEnabled, True)
self.web_page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
self.web_page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
self.deferred = defer.Deferred()
request = QNetworkRequest()
request.setUrl(QUrl(url))
if baseurl:
self._baseUrl = QUrl(baseurl)
self.network_manager.finished.connect(self._requestFinished)
self.network_manager.get(request)
else:
self.web_page.loadFinished.connect(self._loadFinished)
self.web_page.mainFrame().load(request)
示例13: checkWeather
def checkWeather(self):
if self.reply is not None:
return
request = QNetworkRequest()
request.setUrl(QUrl("http://api.liqwei.com/weather/"))
self.reply = self.http.get(request)
self.reply.finished.connect(self.onReplyFinished)
self.reply.error.connect(self.onReplyError)
示例14: prepare_request
def prepare_request(self, url_string):
url = QUrl(url_string)
request = QNetworkRequest()
request.setUrl(url)
request.setRawHeader('User-Agent', 'Cuivre Web Browser')
return request
示例15: get_data
def get_data(self):
request = QNetworkRequest(QUrl(self.config.url))
request.setHeader(QNetworkRequest.ContentTypeHeader, 'text/xml') # or? "text/xml; charset=utf-8"
reply = self.network_manager.post(request, self.xml())
extension = '.zip'
if self.config.jrodos_format == 'application/json':
extension = '.json'
filename = self.config.output_dir + '/' + unicode(self.column) + '_' + unicode(
self.config.jrodos_verticals) + extension
reply.finished.connect(partial(self._data_retrieved, reply, filename))