<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # PyQt 中的`QNetworkAccessManager` > 原文: [http://zetcode.com/pyqt/qnetworkaccessmanager/](http://zetcode.com/pyqt/qnetworkaccessmanager/) PyQt 教程中的`QNetworkAccessManager`展示了如何顯示如何使用`QNetworkAccessManager`發送請求和接收響應。 ## `QNetworkAccessManager` `QNetworkAccessManager`允許應用發送網絡請求和接收回復。 `QNetworkRequest`保留要與網絡管理器發送的請求,`QNetworkReply`包含返回的數據和響應頭。 `QNetworkAccessManager`具有異步 API,這意味著其方法總是立即返回,并且不等到完成時才返回。 而是在請求完成時發出信號。 我們通過附加到完成信號的方法來處理響應。 ## HTTP GET 請求 HTTP GET 方法請求指定資源的表示形式。 `get_request.py` ```py #!/usr/bin/python3 # -*- coding: utf-8 -*- ''' QNetworkAccessManager in PyQt In this example we get a web page. Author: Jan Bodnar Website: zetcode.com Last edited: September 2017 ''' from PyQt5 import QtNetwork from PyQt5.QtCore import QCoreApplication, QUrl import sys class Example: def __init__(self): self.doRequest() def doRequest(self): url = "http://www.something.com" req = QtNetwork.QNetworkRequest(QUrl(url)) self.nam = QtNetwork.QNetworkAccessManager() self.nam.finished.connect(self.handleResponse) self.nam.get(req) def handleResponse(self, reply): er = reply.error() if er == QtNetwork.QNetworkReply.NoError: bytes_string = reply.readAll() print(str(bytes_string, 'utf-8')) else: print("Error occured: ", er) print(reply.errorString()) QCoreApplication.quit() app = QCoreApplication([]) ex = Example() sys.exit(app.exec_()) ``` 該示例檢索指定網頁的 HTML 代碼。 ```py url = "http://www.something.com" req = QtNetwork.QNetworkRequest(QUrl(url)) ``` 使用`QNetworkRequest`,我們將請求發送到指定的 URL。 ```py self.nam = QtNetwork.QNetworkAccessManager() self.nam.finished.connect(self.handleResponse) self.nam.get(req) ``` 創建一個`QNetworkAccessManager`對象。 請求完成后,將調用`handleResponse()`方法。 使用`get()`方法觸發該請求。 ```py def handleResponse(self, reply): er = reply.error() if er == QtNetwork.QNetworkReply.NoError: bytes_string = reply.readAll() print(str(bytes_string, 'utf-8')) else: print("Error occured: ", er) print(reply.errorString()) QCoreApplication.quit() ``` `handleResponse()`接收`QNetworkReply`對象。 它包含已發送請求的數據和標頭。 如果網絡回復中沒有錯誤,我們將使用`readAll()`方法讀取所有數據; 否則,我們將顯示錯誤消息。 `errorString()`返回人類可讀的最后發生的錯誤的描述。 `readAll()`返回`QByteArray`中必須解碼的數據。 ```py $ ./get_request.py <html><head><title>Something.</title></head> <body>Something.</body> </html> ``` 這是輸出。 ## HTTP POST 請求 HTTP POST 方法將數據發送到服務器。 請求正文的類型由`Content-Type`標頭指示。 POST 請求通常通過 HTML 表單發送。 請求中發送的數據可以采用不同的方式進行編碼。 在`application/x-www-form-urlencoded`中,值被編碼為以`'&'`分隔的鍵值元組,鍵和值之間帶有`'='`。 非字母數字字符采用百分比編碼。 `multipart/form-data`用于二進制數據和文件上傳。 `post_request.py` ```py #!/usr/bin/python3 # -*- coding: utf-8 -*- ''' QNetworkAccessManager in PyQt In this example we post data to a web page. Author: Jan Bodnar Website: zetcode.com Last edited: September 2017 ''' from PyQt5 import QtCore, QtGui, QtNetwork import sys, json class Example: def __init__(self): self.doRequest() def doRequest(self): data = QtCore.QByteArray() data.append("name=Peter&") data.append("age=34") url = "https://httpbin.org/post" req = QtNetwork.QNetworkRequest(QtCore.QUrl(url)) req.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader, "application/x-www-form-urlencoded") self.nam = QtNetwork.QNetworkAccessManager() self.nam.finished.connect(self.handleResponse) self.nam.post(req, data) def handleResponse(self, reply): er = reply.error() if er == QtNetwork.QNetworkReply.NoError: bytes_string = reply.readAll() json_ar = json.loads(str(bytes_string, 'utf-8')) data = json_ar['form'] print('Name: {0}'.format(data['name'])) print('Age: {0}'.format(data['age'])) print() else: print("Error occurred: ", er) print(reply.errorString()) QtCore.QCoreApplication.quit() app = QtCore.QCoreApplication([]) ex = Example() sys.exit(app.exec_()) ``` 該示例將發布請求發送到`https://httpbin.org/post`測試站點,該站點將數據以 JSON 格式發送回。 ```py data = QtCore.QByteArray() data.append("name=Peter&") data.append("age=34") ``` 根據規范,我們對`QByteArray`中發送的數據進行編碼。 ```py url = "https://httpbin.org/post" req = QtNetwork.QNetworkRequest(QtCore.QUrl(url)) req.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader, "application/x-www-form-urlencoded") ``` 我們指定`application/x-www-form-urlencoded`編碼類型。 ```py bytes_string = reply.readAll() json_ar = json.loads(str(bytes_string, 'utf-8')) data = json_ar['form'] print('Name: {0}'.format(data['name'])) print('Age: {0}'.format(data['age'])) print() ``` 在處理器方法中,我們讀取響應數據并將其解碼。 使用內置的`json`模塊,我們提取發布的數據。 ```py $ ./post_request.py Name: Peter Age: 34 ``` 這是輸出。 ## 使用`QNetworkAccessManager`進行認證 每當最終服務器在傳遞所請求的內容之前請求認證時,都會發出`authenticationRequired`信號。 `authenticate.py` ```py #!/usr/bin/python3 # -*- coding: utf-8 -*- ''' QNetworkAccessManager in PyQt In this example, we show how to authenticate to a web page. Author: Jan Bodnar Website: zetcode.com Last edited: September 2017 ''' from PyQt5 import QtCore, QtGui, QtNetwork import sys, json class Example: def __init__(self): self.doRequest() def doRequest(self): self.auth = 0 url = "https://httpbin.org/basic-auth/user7/passwd7" req = QtNetwork.QNetworkRequest(QtCore.QUrl(url)) self.nam = QtNetwork.QNetworkAccessManager() self.nam.authenticationRequired.connect(self.authenticate) self.nam.finished.connect(self.handleResponse) self.nam.get(req) def authenticate(self, reply, auth): print("Authenticating") self.auth += 1 if self.auth >= 3: reply.abort() auth.setUser("user7") auth.setPassword("passwd7") def handleResponse(self, reply): er = reply.error() if er == QtNetwork.QNetworkReply.NoError: bytes_string = reply.readAll() data = json.loads(str(bytes_string, 'utf-8')) print('Authenticated: {0}'.format(data['authenticated'])) print('User: {0}'.format(data['user'])) print() else: print("Error occurred: ", er) print(reply.errorString()) QtCore.QCoreApplication.quit() app = QtCore.QCoreApplication([]) ex = Example() sys.exit(app.exec_()) ``` 在示例中,使用`https://httpbin.org`網站顯示如何使用`QNetworkAccessManager`進行認證。 ```py self.nam.authenticationRequired.connect(self.authenticate) ``` 我們將`authenticationRequired`信號連接到`authenticate()`方法。 ```py def authenticate(self, reply, auth): print("Authenticating") ... ``` `authenticate()`方法的第三個參數是`QAuthenticator`,用于傳遞所需的認證信息。 ```py self.auth += 1 if self.auth >= 3: reply.abort() ``` 如果驗證失敗,則`QNetworkAccessManager`會繼續發出`authenticationRequired`信號。 在三次失敗的嘗試之后,我們中止了該過程。 ```py auth.setUser("user7") auth.setPassword("passwd7") ``` 我們將用戶和密碼設置為`QAuthenticator`。 ```py bytes_string = reply.readAll() data = json.loads(str(bytes_string, 'utf-8')) print('Authenticated: {0}'.format(data['authenticated'])) print('User: {0}'.format(data['user'])) print() ``` `https://httpbin.org`用 JSON 數據響應,該數據包含用戶名和指示認證成功的布爾值。 ```py $ ./authenticate.py Authenticating Authenticated: True User: user7 ``` 這是輸出。 ## 提取一個網站圖標 網站圖標是與特定網站相關的小圖標。 在以下示例中,我們將從網站上下載網站圖標。 `fetch_icon.py` ```py #!/usr/bin/python3 # -*- coding: utf-8 -*- ''' QNetworkAccessManager in PyQt In this example we fetch a favicon from a website. Author: Jan Bodnar Website: zetcode.com Last edited: September 2017 ''' from PyQt5 import QtCore, QtGui, QtNetwork import sys class Example: def __init__(self): self.doRequest() def doRequest(self): url = "http://www.google.com/favicon.ico" req = QtNetwork.QNetworkRequest(QtCore.QUrl(url)) self.nam = QtNetwork.QNetworkAccessManager() self.nam.finished.connect(self.handleResponse) self.nam.get(req) def handleResponse(self, reply): er = reply.error() if er == QtNetwork.QNetworkReply.NoError: data = reply.readAll() self.saveFile(data) else: print("Error occured: ", er) print(reply.errorString()) QtCore.QCoreApplication.quit() def saveFile(self, data): f = open('favicon.ico', 'wb') with f: f.write(data) app = QtCore.QCoreApplication([]) ex = Example() sys.exit(app.exec_()) ``` 該代碼示例下載了 Google 的收藏夾圖標。 ```py self.nam.get(req) ``` 我們使用`get()`方法下載圖標。 ```py data = reply.readAll() self.saveFile(data) ``` 在`handleResponse()`方法中,我們讀取數據并將其保存到文件中。 ```py def saveFile(self, data): f = open('favicon.ico', 'wb') with f: f.write(data) ``` 圖像數據以`saveFile()`方法保存在磁盤上。 在本教程中,我們使用了`QNetworkAccessManager`。 您可能也對以下相關教程感興趣: [`QPropertyAnimation`教程](/pyqt/qpropertyanimation/), [PyQt5 教程](/gui/pyqt5/)和 [Python 教程](/lang/python/)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看