当前位置: 首页>>代码示例>>Python>>正文


Python QNetworkRequest.setUrl方法代码示例

本文整理汇总了Python中PyQt5.QtNetwork.QNetworkRequest.setUrl方法的典型用法代码示例。如果您正苦于以下问题:Python QNetworkRequest.setUrl方法的具体用法?Python QNetworkRequest.setUrl怎么用?Python QNetworkRequest.setUrl使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt5.QtNetwork.QNetworkRequest的用法示例。


在下文中一共展示了QNetworkRequest.setUrl方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _load_content

# 需要导入模块: from PyQt5.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkRequest import setUrl [as 别名]
    def _load_content(self, content_type, content):
        """
        This method is for displaying some content of
        such types: local web pages, remote web pages,
        local pdf`s, local videos.

        It should be called like in the following example
        to work correctly:
        self._load_content('local_video', 'some_video.mp4')
        """
        self._main_browser_reset_zoom()  # reset zoom
        if content_type == 'local_url':
            source = config['flask_server_home'] + \
                config['flask_server_local_page_client'] + \
                content  # simply get the file from flask-server by its relative path-id
            # specify type of currently opened file for zoom and scroll methods
            self._cur_filetype = "webpage"
        elif content_type == 'external_url':
            self._cur_filetype = "webpage"
            # no needs required as, link should be given in
            # 'http://yoursite.com/yourpage'
            source = content
        elif content_type == 'local_pdf':
            # to render PDF`s we use PDF.js, so we open its page and send it a
            # path for the target file.
            source = config['flask_server_home'] + \
                config['flask_server_local_page_client'] + \
                content
            self._cur_filetype = "pdf"
        elif content_type == 'local_video':
            # in case of opening local videos we need to modify the path to the video in the source code of
            # the videoplayer, so don`t die after reading this code. It works just in the same style as other
            # filetypes, but in a very weird way.
            source = config['flask_server_home'] + \
                config['flask_server_video_addr_client'] + content
            logger.info('Opening video at {}'.format(source))
            self._cur_filetype = "video"
        # Set a custom user agent to avoid message about deprecated version of
        # browser

        self._main_browser.page().userAgentForUrl = self._custom_ua

        logger.info('Loading data on address: {}'.format(source))

        # Create a request to be able to set user-agent data. Without
        # it, it`s impossible to customize request data.
        request = QNetworkRequest()
        request.setUrl(QUrl(source))
        request.setRawHeader("USER-AGENT", config['output_user_agent'])

        # and finally load the result
        self._main_browser.load(request)
开发者ID:TarasZelyk,项目名称:ariusproject,代码行数:54,代码来源:output_main.py

示例2: request_obj

# 需要导入模块: from PyQt5.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkRequest import setUrl [as 别名]
    def request_obj(self, url, headers=None, body=None):
        """ Return a QNetworkRequest object """
        request = QNetworkRequest()
        request.setUrl(to_qurl(url))
        request.setOriginatingObject(self.web_page.mainFrame())

        if headers is not None:
            self.web_page.skip_custom_headers = True
            self._set_request_headers(request, headers)

        if body and not request.hasRawHeader(b"content-type"):
            # there is POST body but no content-type
            # QT will set this header, but it will complain so better to do this here
            request.setRawHeader(b"content-type", b"application/x-www-form-urlencoded")

        return request
开发者ID:takaaptech,项目名称:splash,代码行数:18,代码来源:browser_tab.py

示例3: download

# 需要导入模块: from PyQt5.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkRequest import setUrl [as 别名]
    def download(self):
        grab = None
        for x in range(self._tilesRect.width()):
            for y in range(self._tilesRect.height()):
                tp = Point(self._tilesRect.topLeft() + QPoint(x, y))
                if tp not in self._tilePixmaps:
                    grab = QPoint(tp)
                    break

        if grab is None:
            self._url = QUrl()
            return

        path = 'http://tile.openstreetmap.org/%d/%d/%d.png' % (self.zoom, grab.x(), grab.y())
        self._url = QUrl(path)
        request = QNetworkRequest()
        request.setUrl(self._url)
        request.setRawHeader(b'User-Agent', b'Nokia (PyQt) Graphics Dojo 1.0')
        request.setAttribute(QNetworkRequest.User, grab)
        self._manager.get(request)
开发者ID:Axel-Erfurt,项目名称:pyqt5,代码行数:22,代码来源:lightmaps.py

示例4: getImage

# 需要导入模块: from PyQt5.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkRequest import setUrl [as 别名]
    def getImage(self, networkAccessManager):
        if not self.image_data.isNull():
            log.debug("Image data for %s is null...", self)
            return self.image_data

        if "multiverseid" not in self._data.keys():
            log.warn("%s does not have a multiverseid, cannot download image.", self)
            return self.image_data

        request = QNetworkRequest()

        log.debug("Checking image cache for %s.png", self.multiverse_id)
        cardURI = self.cachedImageURI.path()[1:] #fix for windows file system
        if os.path.exists(cardURI):
            log.debug("Found %s", cardURI)
            request.setUrl(self.cachedImageURI)
        else:
            log.debug("Downloading image %s", self.imageURL.toString())
            request.setUrl(self.imageURL)

        reply = networkAccessManager.get(request)
        reply.setAttribute(QNetworkRequest.User, self)

        return reply
开发者ID:Acbarakat,项目名称:MtGCubeViz,代码行数:26,代码来源:Card.py

示例5: ForRec

# 需要导入模块: from PyQt5.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkRequest import setUrl [as 别名]
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply, QSslConfiguration, QSsl
from PyQt5.QtCore import QUrl


class ForRec(QNetworkAccessManager):
	def Reqest(self,reply):
		print(reply.readAll())
   

if __name__ == '__main__':

	url = "https://api.telegram.org/bot"

	manager = QNetworkAccessManager()
	request = QNetworkRequest()

	config = QSslConfiguration.defaultConfiguration()
	config.setProtocol(QSsl.SecureProtocols)

	request.setSslConfiguration(config)
	request.setUrl(QUrl(url));
	request.setHeader(QNetworkRequest.ServerHeader, "getUpdates")

	#manager.get(request)




开发者ID:iphizic,项目名称:PyTeleBot,代码行数:26,代码来源:main.py

示例6: SearchThread

# 需要导入模块: from PyQt5.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkRequest import setUrl [as 别名]
class SearchThread(QThread):
    domain = 'kyfw.12306.cn' #请求域名(真实连接地址)
    host='kyfw.12306.cn' #请求的域名(host)
    http = requests.session()
    stopSignal=False
    threadId=1
    leftTicketUrl="leftTicket/query"
    requests.packages.urllib3.disable_warnings()

    searchThreadCallback= pyqtSignal(list)

    def __init__(self,from_station,to_station,train_date,threadId,leftTicketUrl,interval=2,domain=''):
        super(SearchThread,self).__init__()
        if domain!='':
            self.domain=domain

        self.threadId=threadId
        self.from_station=from_station
        self.to_station=to_station
        self.train_date=train_date
        self.interval=interval
        self.leftTicketUrl=leftTicketUrl


    def run(self):
        time.sleep(self.threadId)

        userAgent="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36"
        headers={'Referer':'https://kyfw.12306.cn/otn/leftTicket/init',"host":self.host\
            ,'Cache-Control':'no-cache','Pragma':"no-cache","User-Agent":userAgent,"X-Requested-With":"XMLHttpRequest"}

        t=str(random.random())

        dataUrl='?leftTicketDTO.train_date='+self.train_date\
            +"&leftTicketDTO.from_station="+self.stationCode[self.from_station]+"&leftTicketDTO.to_station="+\
            self.stationCode[self.to_station]+"&purpose_codes=ADULT"

        logUrl='https://' + self.domain + '/otn/leftTicket/log'+dataUrl
        url='https://' + self.domain + '/otn/'+self.leftTicketUrl+dataUrl


        self.http.get(logUrl,verify=False,headers=headers)
        jc_fromStation=xxtea.unicodeStr(self.from_station+","+self.stationCode[self.from_station])
        jc_toStation=xxtea.unicodeStr(self.to_station+","+self.stationCode[self.to_station])
        self.http.cookies.set("_jc_save_fromStation",jc_fromStation)
        self.http.cookies.set("_jc_save_toStation",jc_toStation)
        self.http.cookies.set('_jc_save_fromDate',self.train_date)
        self.http.cookies.set('_jc_save_toDate',"2014-01-01")
        self.http.cookies.set('_jc_save_wfdc_flag','dc')

        ret=self.http.get(url,verify=False,headers=headers)
        ticketInfo=ret.json()

        if ticketInfo['status']!=True :
            print(ticketInfo)

        cookies=self.http.cookies.get_dict()
        cookieStr=";".join('%s=%s' % (key, value) for (key, value) in cookies.items())

        self.http.get(logUrl,verify=False,headers=headers)
        self.req=QNetworkRequest()
        self.req.setUrl(QUrl(url))
        self.req.setRawHeader("Referer","https://kyfw.12306.cn/otn/leftTicket/init")
        self.req.setRawHeader("host",self.host)
        self.req.setRawHeader("Cache-Control","no-cache")
        self.req.setRawHeader("Pragma","no-cache")
        self.req.setRawHeader("User-Agent",userAgent)
        self.req.setRawHeader("Cookie",cookieStr)

        while not self.stopSignal:
            mutex.acquire(1)
            self.search_ticket(self.from_station,self.to_station,self.train_date)
            mutex.release(1)
            time.sleep(self.interval)


    def search_ticket(self, fromStation, toStation, date):
        try:
            self.netWorkManager=QNetworkAccessManager()
            self.reply=self.netWorkManager.get(self.req)
            self.reply.ignoreSslErrors()
            self.reply.finished.connect(self.search_finished)
            self.exec()

        except Exception as e:
            print("ip:"+self.domain+"查询发生错误:"+e.__str__())
            return False



    def search_finished(self):
        try:
            ret=self.reply.readAll()
            ret=str(ret,'utf8')
            ticketInfo=json.loads(ret)
            self.reply=None
            self.netWorkManager=None
            self.exit()
            if ticketInfo['status']!=True or ticketInfo['messages']!=[] :
                print(self.domain)
#.........这里部分代码省略.........
开发者ID:asd1355215911,项目名称:xilinTicketV2,代码行数:103,代码来源:searchthread.py

示例7: _make_request

# 需要导入模块: from PyQt5.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkRequest import setUrl [as 别名]
 def _make_request(self, url):
     request = QNetworkRequest()
     request.setUrl(QUrl(url))
     return request
开发者ID:blropb,项目名称:qt-test,代码行数:6,代码来源:test.py

示例8: Browser

# 需要导入模块: from PyQt5.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkRequest import setUrl [as 别名]
class Browser(QObject):

    comment_postdata_example = {
            'ft_ent_identifier': '735272899920440', # ИД сообщения
            'comment_text': 'Cool))', # Текст коментария
            'source': '22',
            'client_id': '1429632677205%3A3425397009',
            'reply_fbid': '',
            'parent_comment_id': '',
            'rootid': 'u_ps_0_0_k',
            'clp': '',
            'attached_sticker_fbid': '0',
            'attached_photo_fbid': '0',
            'feed_context': '%7B%22fbfeed_context%22%3Atrue%2C%22location_type%22%3A36%2C%22is_starred%22%3Afalse%2C%22is_pinned_post%22%3Afalse%2C%22can_moderate_timeline_story%22%3Afalse%2C%22profile_id%22%3A308106089303792%2C%22outer_object_element_id%22%3A%22u_ps_0_0_0%22%2C%22object_element_id%22%3A%22u_ps_0_0_0%22%2C%22is_ad_preview%22%3Afalse%2C%22is_editable%22%3Afalse%7D',
            'ft[tn]': '[]',
            'ft[top_level_post_id]': '750869418360788',
            'ft[fbfeed_location]': '36',
            'nctr[_mod]': 'pagelet_timeline_main_column',
            'av': '100009110845526',
            '__user': '100009110845526',
            '__a': '1',
            '__dyn': '', #пустой
            '__req': 'c',
            'fb_dtsg': 'AQEkxiOYhtrJ', # инпут в теле документа
            'ttstamp': '26581716611911872109105876676',
            '__rev': '1713404',
        }

    def __init__(self, parent):
        super().__init__(parent)
        self.set_url('http://google.ru')
        conn = QNetworkAccessManager()
        self.conn = conn
        self.r = QNetworkRequest()
        self.r.attribute(QNetworkRequest.CookieSaveControlAttribute, QVariant(True))
        # self.r.setHeader(QNetworkRequest.ContentTypeHeader, "application/x-www-form-urlencoded")
        # self.r.setRawHeader("Referer", "http://www.facebook.com/")
        # self.r.setRawHeader("Host", "www.facebook.com")
        self.cj = QNetworkCookieJar()
        conn.setCookieJar(self.cj)
        conn.createRequest = self._create_request
        self.wv = WebView()
        self.wv.show()
        self.wv.page().setNetworkAccessManager(conn)
        # self.wv.auth()
        self.loop = QEventLoop()
        pass

    def _create_request(self, operation, request, data):
        # print(data)
        reply = QNetworkAccessManager.createRequest(self.conn,
                                                    operation,
                                                    request,
                                                    data)
        self.conn.new_reply = reply
        self.wv_reply = reply
        return reply

    def set_url(self, url):
        if isinstance(url, QByteArray):
            self.url = QUrl().fromEncoded(url)
        else:
            self.url = QUrl(url)

    def send_request(self, post=None, data={}):
        loop = QEventLoop()
        self.r.setUrl(self.url)
        if post:
            encoded_data = self._urlencode_post_data(data)
            pprint(encoded_data)
            self.reply_post = self.conn.post(self.r, encoded_data)
            self.reply_post.downloadProgress.connect(self.prepare_responce)

        else:
            self.reply = self.conn.get(self.r)
            self.reply.finished.connect(self.prepare_responce)
        # return \
        loop.exec()

    def prepare_responce(self):
        # self.check_redirect()
        self.responce = self.reply_post.readAll()#.data().decode('utf-8')
        pprint(self.responce)
        sys.exit()

    def check_redirect(self):
        print(self.url)
        a = self.reply.rawHeader('Location')

        if len(a) > 0:
            self.set_url(a)
            self.send_request()
        else:
            self.loop.exit()

    def test(self):
        self.wv.auth('https://www.facebook.com/freelanceuidesignerdeveloper')
        self.wv.authentication.connect(self.webview_login)

    def _urlencode_post_data(self, post_data):
#.........这里部分代码省略.........
开发者ID:blropb,项目名称:qt-test,代码行数:103,代码来源:browser.py

示例9: E5XmlRpcClient

# 需要导入模块: from PyQt5.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkRequest import setUrl [as 别名]
class E5XmlRpcClient(QObject):
    """
    Class implementing a xmlrpc client for Qt.
    """
    def __init__(self, url, parent=None):
        """
        Constructor
        
        @param url xmlrpc handler URL (string or QUrl)
        @param parent parent object (QObject)
        """
        super(E5XmlRpcClient, self).__init__(parent)
        
        # attributes for the network objects
        self.__networkManager = QNetworkAccessManager(self)
        self.__networkManager.proxyAuthenticationRequired.connect(
            proxyAuthenticationRequired)
        self.__networkManager.finished.connect(self.__replyFinished)
        if SSL_AVAILABLE:
            self.__sslErrorHandler = E5SslErrorHandler(self)
            self.__networkManager.sslErrors.connect(self.__sslErrors)
        
        self.__callmap = {}
        
        self.__request = QNetworkRequest(QUrl(url))
        self.__request.setRawHeader(b"User-Agent", b"E5XmlRpcClient/1.0")
        self.__request.setHeader(QNetworkRequest.ContentTypeHeader, "text/xml")
    
    def setUrl(self, url):
        """
        Public slot to set the xmlrpc handler URL.
        
        @param url xmlrpc handler URL (string or QUrl)
        """
        url = QUrl(url)
        if url.isValid():
            self.__request.setUrl(url)
    
    def call(self, method, args, responseCallback, errorCallback):
        """
        Public method to call the remote server.
        
        @param method name of the remote method to be called (string)
        @param args tuple of method arguments (tuple)
        @param responseCallback method to be called with the returned
            result as a tuple (function)
        @param errorCallback method to be called in case of an error
            with error code and error string (function)
        """
        assert isinstance(args, tuple), \
            "argument must be tuple or Fault instance"
        
        data = xmlrpc.dumps(args, method).encode("utf-8")
        reply = self.__networkManager.post(
            self.__request, QByteArray(data))
        self.__callmap[reply] = (responseCallback, errorCallback)
    
    def abort(self):
        """
        Public method to abort all calls.
        """
        for reply in list(self.__callmap):
            if reply.isRunning():
                reply.abort()
    
    def __sslErrors(self, reply, errors):
        """
        Private slot to handle SSL errors.
        
        @param reply reference to the reply object (QNetworkReply)
        @param errors list of SSL errors (list of QSslError)
        """
        ignored = self.__sslErrorHandler.sslErrorsReply(reply, errors)[0]
        if ignored == E5SslErrorHandler.NotIgnored and reply in self.__callmap:
            self.__callmap[reply][1](xmlrpc.TRANSPORT_ERROR, self.tr(
                "SSL Error"))
    
    def __replyFinished(self, reply):
        """
        Private slot handling the receipt of a reply.
        
        @param reply reference to the finished reply (QNetworkReply)
        """
        if reply not in self.__callmap:
            return
        
        if reply.error() != QNetworkReply.NoError:
            self.__callmap[reply][1](xmlrpc.TRANSPORT_ERROR,
                                     reply.errorString())
        else:
            data = bytes(reply.readAll()).decode("utf-8")
            try:
                data = xmlrpc.loads(data)[0]
                self.__callmap[reply][0](data)
            except xmlrpc.Fault as fault:
                self.__callmap[reply][1](fault.faultCode, fault.faultString)
        
        reply.deleteLater()
        del self.__callmap[reply]
开发者ID:pycom,项目名称:EricShort,代码行数:101,代码来源:E5XmlRpcClient.py

示例10: FLNetwork

# 需要导入模块: from PyQt5.QtNetwork import QNetworkRequest [as 别名]
# 或者: from PyQt5.QtNetwork.QNetworkRequest import setUrl [as 别名]
class FLNetwork(QtCore.QObject):

    url = None
    request = None
    manager = None

    reply = None

    finished = QtCore.pyqtSignal()
    start = QtCore.pyqtSignal()
    data = QtCore.pyqtSignal(str)
    dataTransferProgress = QtCore.pyqtSignal(int, int)

    def __init__(self, url):
        super(FLNetwork, self).__init__()
        self.url = url
        from PyQt5.QtNetwork import QNetworkRequest, QNetworkAccessManager
        self.request = QNetworkRequest()

        self.manager = QNetworkAccessManager()
        # self.manager.readyRead.connect(self._slotNetworkStart)
        self.manager.finished['QNetworkReply*'].connect(self._slotNetworkFinished)
        # self.data.connect(self._slotNetWorkData)
        # self.dataTransferProgress.connect(self._slotNetworkProgress)

    @decorators.BetaImplementation
    def get(self, location):
        self.request.setUrl(QtCore.QUrl("%s%s" % (self.url, location)))
        self.reply = self.manager.get(self.request)
        try:
            self.reply.uploadProgress.disconnect(self._slotNetworkProgress)
            self.reply.downloadProgress.disconnect(self._slotNetworkProgress)
        except:
            pass

        self.reply.downloadProgress.connect(self._slotNetworkProgress)

    @decorators.BetaImplementation
    def put(self, data, location):
        self.request.setUrl(QtCore.QUrl("%s%s" % (self.url, localtion)))
        self.reply = self.manager.put(data, self.request)
        try:
            self.reply.uploadProgress.disconnect(self._slotNetworkProgress)
            self.reply.downloadProgress.disconnect(self._slotNetworkProgress)
        except:
            pass
        self.uploadProgress.connect(self.slotNetworkProgress)

    @decorators.BetaImplementation
    def copy(self, fromLocation, toLocation):
        self.request.setUrl("%s%s" % (self.url, fromLocaltion))
        data = self.manager.get(self.request)
        self.put(data.readAll(), toLocation)

    @QtCore.pyqtSlot()
    def _slotNetworkStart(self):
        self.start.emit()

    @QtCore.pyqtSlot()
    def _slotNetworkFinished(self, reply=None):
        self.finished.emit()

    #@QtCore.pyqtSlot(QtCore.QByteArray)
    # def _slotNetWorkData(self, b):
    #    buffer = b
    #    self.data.emit(b)

    def _slotNetworkProgress(self, bDone, bTotal):
        self.dataTransferProgress.emit(bDone, bTotal)
        data_ = None
        reply_ = self.reply.readAll().data()
        try:
            data_ = str(reply_, encoding="iso-8859-15")
        except:
            data_ = str(reply_, encoding="utf-8")

        self.data.emit(data_)
开发者ID:juanjosepablos,项目名称:pineboo,代码行数:79,代码来源:flnetwork.py


注:本文中的PyQt5.QtNetwork.QNetworkRequest.setUrl方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。