本文整理汇总了Python中PyQt4.QtNetwork.QNetworkRequest方法的典型用法代码示例。如果您正苦于以下问题:Python QtNetwork.QNetworkRequest方法的具体用法?Python QtNetwork.QNetworkRequest怎么用?Python QtNetwork.QNetworkRequest使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtNetwork
的用法示例。
在下文中一共展示了QtNetwork.QNetworkRequest方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: createRequest
# 需要导入模块: from PyQt4 import QtNetwork [as 别名]
# 或者: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
def createRequest(self, op, request, device=None):
""" Reimplemented to enable adblock/url-block """
if op!=self.GetOperation or request.url().scheme()=='file':
return QtNetwork.QNetworkAccessManager.createRequest(self, op, request, device)
url = unicode(request.url().toString())
block = False
# Font blocking capability
if block_fonts:
if '.ttf' in url or '.woff' in url:
block = True
# AdBlocking Feature
if enable_adblock:
for ad in ad_strings:
if ad in url:
block = True
break
if block:
# print("Blocked: "+url)
return QtNetwork.QNetworkAccessManager.createRequest(self, op, QtNetwork.QNetworkRequest(QtCore.QUrl()), device)
reply = QtNetwork.QNetworkAccessManager.createRequest(self, op, request, device)
#reply.metaDataChanged.connect(self.gotMetadata)
return reply
示例2: downloadVideo
# 需要导入模块: from PyQt4 import QtNetwork [as 别名]
# 或者: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
def downloadVideo(self):
url = unicode(self.tabWidget.currentWidget().url().toString())
# For youtube videos
if validYoutubeUrl(url):
vid_id = parse_qs(urlparse(url).query)['v'][0]
url = 'https://m.youtube.com/watch?v=' + vid_id
yt = YouTube(url) # Use PyTube module for restricted videos
videos = yt.get_videos()
dialog = youtube_dialog.YoutubeDialog(videos, self)
if dialog.exec_() == 1 :
index = abs(dialog.buttonGroup.checkedId())-2
vid = videos[index]
reply = networkmanager.get( QNetworkRequest(QUrl.fromUserInput(vid.url)) )
self.handleUnsupportedContent(reply, vid.filename + '.' + vid.extension)
return
# For embeded HTML5 videos
request = QNetworkRequest(self.video_URL)
request.setRawHeader('Referer', self.video_page_url)
reply = networkmanager.get(request)
self.handleUnsupportedContent(reply)
示例3: startDownload
# 需要导入模块: from PyQt4 import QtNetwork [as 别名]
# 或者: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
def startDownload(self, req):
loop = QtCore.QEventLoop()
QtCore.QTimer.singleShot(5000, loop.quit)
self.reply = self.networkmanager.get(req)
self.reply.metaDataChanged.connect(loop.quit)
loop.exec_()
#wait(1000)
if self.reply.hasRawHeader('Location'):
URL = QtCore.QUrl.fromUserInput(unicode(self.reply.rawHeader('Location')))
self.reply.abort()
req = QtNetwork.QNetworkRequest(URL)
req.setRawHeader('User-Agent', self.useragent)
self.startDownload(req)
return
print str(self.reply.url().toString().toUtf8())
if self.reply.isFinished():
self.dataReceived()
self.downloadStopped()
return
self.reply.finished.connect(self.downloadStopped)
#self.reply.readyRead.connect(self.dataReceived)
self.reply.error.connect(self.downloadError)
示例4: createRequest
# 需要导入模块: from PyQt4 import QtNetwork [as 别名]
# 或者: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
def createRequest(self, op, request, device = None ):
global lst
try:
path = str(request.url().path())
except UnicodeEncodeError:
pass
lower_case = path.lower()
#lst = tuple(open("easylist.txt", 'r'))
lst = ["doubleclick.net" ,"ads",'.jpg','redirector','itag=','.png','.gif','.css','google','facebook','.aspx',r"http[^'].mp4",r"http[^'].flv", r"||youtube-nocookie.com/gen_204?", r"youtube.com###watch-branded-actions", "imagemapurl","b.scorecardresearch.com","rightstuff.com","scarywater.net","popup.js","banner.htm","_tribalfusion","||n4403ad.doubleclick.net^$third-party",".googlesyndication.com","graphics.js","fonts.googleapis.com/css","s0.2mdn.net","server.cpmstar.com","||banzai/banner.$subdocument","@@||anime-source.com^$document","google","/pagead2.","frugal.gif","jriver_banner.png","show_ads.js",'##a[href^="http://billing.frugalusenet.com/"]',"http://jriver.com/video.html","||animenewsnetwork.com^*.aframe?","||contextweb.com^$third-party",".gutter",".iab",'http://www.animenewsnetwork.com/assets/[^"]*.jpg']
block = False
for l in lst:
if lower_case.find(l) != -1:
block = True
break
if block:
print ("Skipping")
print (request.url().path())
return QNetworkAccessManager.createRequest(self, QNetworkAccessManager.GetOperation, QtNetwork.QNetworkRequest(QtCore.QUrl()))
else:
return QNetworkAccessManager.createRequest(self, op, request, device)
示例5: createRequest
# 需要导入模块: from PyQt4 import QtNetwork [as 别名]
# 或者: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
def createRequest(self, op, request, device = None ):
global block_list
try:
path = str(request.url().toString())
except UnicodeEncodeError:
path = str(request.url().path())
pass
lower_path = path.lower()
#lst = tuple(open("easylist.txt", 'r'))
block_list = ["doubleclick.net" ,"ads", r"||youtube-nocookie.com/gen_204?", r"youtube.com###watch-branded-actions", "imagemapurl","b.scorecardresearch.com","rightstuff.com","scarywater.net","popup.js","banner.htm","_tribalfusion","||n4403ad.doubleclick.net^$third-party",".googlesyndication.com","graphics.js","fonts.googleapis.com/css","s0.2mdn.net","server.cpmstar.com","||banzai/banner.$subdocument","@@||anime-source.com^$document","/pagead2.","frugal.gif","jriver_banner.png","show_ads.js",'##a[href^="http://billing.frugalusenet.com/"]',"http://jriver.com/video.html","||animenewsnetwork.com^*.aframe?","||contextweb.com^$third-party",".gutter",".iab",'http://www.animenewsnetwork.com/assets/[^"]*.jpg','revcontent']
block = False
for l in block_list:
if l in lower_path:
block = True
break
if block:
print ("Skipping")
print (path)
return QNetworkAccessManager.createRequest(self, QNetworkAccessManager.GetOperation, QtNetwork.QNetworkRequest(QtCore.QUrl()))
else:
return QNetworkAccessManager.createRequest(self, op, request, device)
示例6: ask_for_token
# 需要导入模块: from PyQt4 import QtNetwork [as 别名]
# 或者: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
def ask_for_token(self, c_id, c_secret):
"""Ask a token from Isogeo API authentification page.
This send a POST request to Isogeo API with the user id and secret in
its header. The API should return an access token
"""
headervalue = "Basic " + base64.b64encode(c_id + ":" + c_secret)
data = urllib.urlencode({"grant_type": "client_credentials"})
databyte = QByteArray()
databyte.append(data)
url = QUrl('https://id.api.isogeo.com/oauth/token')
request = QNetworkRequest(url)
request.setRawHeader("Authorization", headervalue)
if self.requestStatusClear is True:
self.requestStatusClear = False
token_reply = self.manager.post(request, databyte)
token_reply.finished.connect(
partial(self.handle_token, answer=token_reply))
QgsMessageLog.logMessage("Authentication succeeded", "Isogeo")
示例7: send_request_to_isogeo_api
# 需要导入模块: from PyQt4 import QtNetwork [as 别名]
# 或者: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
def send_request_to_isogeo_api(self, token, limit=10):
"""Send a content url to the Isogeo API.
This takes the currentUrl variable and send a request to this url,
using the token variable.
"""
myurl = QUrl(self.currentUrl)
request = QNetworkRequest(myurl)
request.setRawHeader("Authorization", token)
if self.requestStatusClear is True:
self.requestStatusClear = False
api_reply = self.manager.get(request)
api_reply.finished.connect(
partial(self.handle_api_reply, answer=api_reply))
else:
pass
# REQUEST and RESULTS ----------------------------------------------------
示例8: ask_for_token
# 需要导入模块: from PyQt4 import QtNetwork [as 别名]
# 或者: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
def ask_for_token(c_id, c_secret, request_status=True):
"""Ask a token from Isogeo API authentification page.
This send a POST request to Isogeo API with the user id and secret in
its header. The API should return an access token
"""
headervalue = "Basic " + base64.b64encode(c_id + ":" + c_secret)
data = urllib.urlencode({"grant_type": "client_credentials"})
databyte = QByteArray()
databyte.append(data)
url = QUrl('https://id.api.isogeo.com/oauth/token')
request = QNetworkRequest(url)
request.setRawHeader("Authorization", headervalue)
if request_status is True:
request_status = False
return request, databyte
QgsMessageLog.logMessage("Authentication succeeded", "Isogeo")
示例9: request
# 需要导入模块: from PyQt4 import QtNetwork [as 别名]
# 或者: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
def request( url, params=None, secure=False, extraHeaders=None, successHandler=None, failureHandler=None, finishedHandler=None, parent=None ):
global nam, _isSecureSSL
if _isSecureSSL==False and False: #Warn the user of a potential security risk
msgRes = QtGui.QMessageBox.warning( None, QtCore.QCoreApplication.translate("NetworkService", "Insecure connection"),
QtCore.QCoreApplication.translate("Updater", "The cacerts.pem file is missing or invalid. Your passwords and data will be send unsecured! Continue without encryption? If unsure, choose \"abort\"!"),
QtCore.QCoreApplication.translate("NetworkService", "Continue in unsecure mode"),
QtCore.QCoreApplication.translate("NetworkService", "Abort") )
if msgRes==0:
_isSecureSSL=None
else:
sys.exit(1)
if secure:
key=securityTokenProvider.getKey()
if not params:
params = {}
params["skey"] = key
if url.lower().startswith("http"):
reqURL = QUrl(url)
else:
reqURL = QUrl( NetworkService.url+url )
req = QNetworkRequest( reqURL )
if extraHeaders:
for k, v in extraHeaders.items():
req.setRawHeader( k, v )
if params:
if isinstance( params, dict):
multipart, boundary = NetworkService.genReqStr( params )
req.setRawHeader( "Content-Type", b'multipart/form-data; boundary='+boundary+b'; charset=utf-8')
elif isinstance( params, bytes ):
req.setRawHeader( "Content-Type", b'application/x-www-form-urlencoded' )
multipart = params
else:
print( params )
print( type( params ) )
return( RequestWrapper( nam.post( req, multipart ), url=url ).getResult() )
else:
return( RequestWrapper( nam.get( req ), url=url).getResult() )
示例10: resumeDownload
# 需要导入模块: from PyQt4 import QtNetwork [as 别名]
# 或者: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
def resumeDownload(self):
self.file = QtCore.QFile(self.filepath, self)
request = QtNetwork.QNetworkRequest(QtCore.QUrl(self.url))
if self.support_resume:
self.loadedsize = self.file.size()
if str(self.loadedsize) == self.totalsize : return
request.setRawHeader('Range', 'bytes={}-'.format(self.loadedsize) )
else:
self.file.resize(0)
self.loadedsize = 0
self.download = self.nam.get(request)
示例11: downloadFile
# 需要导入模块: from PyQt4 import QtNetwork [as 别名]
# 或者: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
def downloadFile(self, index=0):
self.file = QtCore.QFile(self.download_list[index][0], self)
if self.file.exists():
self.file.resize(0)
req = QtNetwork.QNetworkRequest(QtCore.QUrl.fromUserInput(self.download_list[index][1]))
req.setRawHeader('User-Agent', self.useragent)
self.startDownload(req)
示例12: downloadLink
# 需要导入模块: from PyQt4 import QtNetwork [as 别名]
# 或者: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
def downloadLink(self):
request = QtNetwork.QNetworkRequest(QtCore.QUrl.fromUserInput(self.text()))
self.downloadRequested.emit(request)
示例13: asyncFetchIssueCoverURLs
# 需要导入模块: from PyQt4 import QtNetwork [as 别名]
# 或者: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
def asyncFetchIssueCoverURLs( self, issue_id ):
self.issue_id = issue_id
details = self.fetchCachedIssueSelectDetails( issue_id )
if details['image_url'] is not None:
self.urlFetchComplete.emit( details['image_url'],details['thumb_image_url'], self.issue_id )
return
issue_url = self.api_base_url + "/issue/" + CVTypeID.Issue + "-" + str(issue_id) + "/?api_key=" + self.api_key + "&format=json&field_list=image,cover_date,site_detail_url"
self.nam = QNetworkAccessManager()
self.nam.finished.connect( self.asyncFetchIssueCoverURLComplete )
self.nam.get(QNetworkRequest(QUrl(issue_url)))
示例14: asyncFetchAlternateCoverURLs
# 需要导入模块: from PyQt4 import QtNetwork [as 别名]
# 或者: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
def asyncFetchAlternateCoverURLs( self, issue_id, issue_page_url ):
# This async version requires the issue page url to be provided!
self.issue_id = issue_id
url_list = self.fetchCachedAlternateCoverURLs( issue_id )
if url_list is not None:
self.altUrlListFetchComplete.emit( url_list, int(self.issue_id) )
return
self.nam = QNetworkAccessManager()
self.nam.finished.connect( self.asyncFetchAlternateCoverURLsComplete )
self.nam.get(QNetworkRequest(QUrl(str(issue_page_url))))
示例15: fetch
# 需要导入模块: from PyQt4 import QtNetwork [as 别名]
# 或者: from PyQt4.QtNetwork import QNetworkRequest [as 别名]
def fetch( self, url, user_data=None, blocking=False ):
"""
If called with blocking=True, this will block until the image is
fetched.
If called with blocking=False, this will run the fetch in the
background, and emit a signal when done
"""
self.user_data = user_data
self.fetched_url = url
# first look in the DB
image_data = self.get_image_from_cache( url )
if blocking:
if image_data is None:
try:
image_data = urllib.urlopen(url).read()
except Exception as e:
print e
raise ImageFetcherException("Network Error!")
# save the image to the cache
self.add_image_to_cache( self.fetched_url, image_data )
return image_data
else:
# if we found it, just emit the signal asap
if image_data is not None:
self.fetchComplete.emit( QByteArray(image_data), self.user_data )
return
# didn't find it. look online
self.nam = QNetworkAccessManager()
self.nam.finished.connect(self.finishRequest)
self.nam.get(QNetworkRequest(QUrl(url)))
#we'll get called back when done...