詳解如何優(yōu)雅的用PyQt訪問http
使用pydantic或dataclaass創(chuàng)建一個數(shù)據(jù)存儲對象
第一種
# coding: utf-8 from typing import Any import requests from pydantic import Field, BaseModel class ResponseModel(BaseModel): status: bool = Field(True, description="響應(yīng)狀態(tài)") message: str = Field('請求成功', description="響應(yīng)信息") error: str = Field('', description="錯誤信息") response: requests.Response = Field(None, description="響應(yīng)對象") result: Any = Field({}, description="響應(yīng)數(shù)據(jù)") class Config: arbitrary_types_allowed = True
線程
# coding: utf-8 from PySide6.QtCore import QThread, Signal, Slot from common.models import ResponseModel from loguru import logger class RequestThread(QThread): modelChanged = Signal(ResponseModel) def __init__(self, parent=None): super().__init__(parent) self.request = None def run(self): if not self.request: return try: result = self.request() self.modelChanged.emit( ResponseModel( result=result, ) ) except Exception as e: logger.error(e) self.modelChanged.emit( ResponseModel( status=False, message='請求失敗', error=e, ) ) def setRequest(self, request): self.request = request if not self.isRunning(): self.start()
使用函數(shù)將請求對象加入至線程中
import requests from PySide6.QtCore import QCoreApplication from common.models import ResponseModel from request_thread import RequestThread def baidu_request(): response = requests.get('http://www.baidu.com') response.encoding = 'utf-8' return response.text def response_handler(response_model: ResponseModel): if response_model.status: # TODO: 當(dāng)請求正確時處理邏輯 print(response_model.result) pass else: # TODO: 當(dāng)請求錯誤時處理邏輯 print(response_model.message, response_model.error) if __name__ == '__main__': app = QCoreApplication([]) thread = RequestThread() thread.modelChanged.connect(response_handler) thread.finished.connect(app.quit) thread.setRequest(baidu_request) app.exec()
第二種
model模型
# coding: utf-8 from typing import Union, Any from pydantic import BaseModel, Field class RequestModel(BaseModel): method: str = Field('GET', description='請求方法,如 GET、POST、PUT、DELETE') url: str = Field(..., description='請求的 URL 地址') params: dict = Field(None, description='請求參數(shù),如 GET 請求時附帶的參數(shù)') data: dict = Field(None, description='請求數(shù)據(jù),如 POST 請求時提交的數(shù)據(jù)') json_: dict = Field(None, description='請求數(shù)據(jù),如 POST 請求時提交的 json 數(shù)據(jù)', alias='json') headers: dict = Field(None, description='請求頭,如 Content-Type、User-Agent 等') cookies: dict = Field(None, description='請求 cookies,如登錄后獲取的 cookie') files: dict = Field(None, description='上傳的文件,如 POST 請求時上傳的文件') auth: Union[tuple, list] = Field(None, description='HTTP 認(rèn)證,如 Basic 認(rèn)證') timeout: int = Field(None, description='請求超時時間,單位為秒') allow_redirects: bool = Field(True, description='是否允許重定向') proxies: dict = Field(None, description='代理設(shè)置') hooks: Any = Field(None, description='鉤子函數(shù)') stream: bool = Field(False, description='是否以流的形式響應(yīng)') verify: bool = Field(False, description='是否驗(yàn)證 SSL 證書') cert: Union[str, tuple] = Field(None, description='客戶端 SSL 證書') class Config: arbitrary_types_allowed = True class ResponseModel(BaseModel): status: bool = Field(True, description="響應(yīng)狀態(tài)") message: str = Field('請求成功', description="響應(yīng)信息") error: str = Field('', description="錯誤信息") response: requests.Response = Field(None, description="響應(yīng)對象") result: Any = Field({}, description="響應(yīng)數(shù)據(jù)") class Config: arbitrary_types_allowed = True
請求
# coding: utf-8 import requests from PyQt5.QtCore import pyqtSignal from pydantic import BaseModel from queue import Queue from ..models import ResponseModel, RequestModel requests.packages.urllib3.disable_warnings() class RequestThread(QThread): responseChanged = pyqtSignal(BaseModel) def __init__(self, parent=None): super().__init__(parent) self.queue = Queue() def run(self): while not self.queue.empty(): method = self.queue.get() # type: RequestModel try: data = method.model_dump(mode='python') data['json'] = data.pop('json_', None) response = requests.request(**data) response.raise_for_status() self.responseChanged.emit(ResponseModel(response=response)) except requests.exceptions.RequestException as e: self.responseChanged.emit(ResponseModel(status=False, message='請求失敗',error=str(e))) def setRequest(self, method: RequestModel): self.queue.put(method) if not self.isRunning(): self.start()
運(yùn)用
from PyQt5.QtWidgets import QApplication from common import RequestThread, RequestModel, ResponseModel def response_handler(response_model: ResponseModel): if response_model.status: # TODO: 當(dāng)請求正確時處理邏輯 print(response_model.response.text) pass else: # TODO: 當(dāng)請求錯誤時處理邏輯 print(response_model.message, response_model.error) # Create a QApplication instance app = QApplication([]) # Create a request thread and start it request_thread = RequestThread() request_thread.responseChanged.connect(response_handler) request_thread.setRequest(RequestModel(url='http://www.baidu.com')) request_thread.finished.connect(app.quit) app.exec_()
到此這篇關(guān)于詳解如何優(yōu)雅的用PyQt訪問http的文章就介紹到這了,更多相關(guān)PyQt訪問http內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Python如何循環(huán)遍歷Numpy中的Array
Numpy是Python中常見的數(shù)據(jù)處理庫,是數(shù)據(jù)科學(xué)中經(jīng)常使用的庫。在本文中,我們將學(xué)習(xí)如何迭代遍歷訪問矩陣中的元素,需要的可以參考一下2022-04-04Python中實(shí)現(xiàn)三目運(yùn)算的方法
這篇文章主要介紹了Python中實(shí)現(xiàn)三目運(yùn)算的方法,本文用and/or 運(yùn)算符模擬實(shí)現(xiàn)三目運(yùn)算,需要的朋友可以參考下2015-06-06python 函數(shù)進(jìn)階之閉包函數(shù)
這篇文章主要介紹了python 函數(shù)進(jìn)階之閉包函數(shù),內(nèi)函數(shù)使用了外函數(shù)的局部變量,并且外函數(shù)把內(nèi)函數(shù)返回出來的過程叫做閉包,里面的內(nèi)函數(shù)是閉包函數(shù),下文相關(guān)介紹需要的小伙伴可以參考一下2022-04-04在Python中利用Into包整潔地進(jìn)行數(shù)據(jù)遷移的教程
這篇文章主要介紹了在Python中如何利用Into包整潔地進(jìn)行數(shù)據(jù)遷移,在數(shù)據(jù)格式的任意兩個格式之間高效地遷移數(shù)據(jù),需要的朋友可以參考下2015-03-03python+pyqt實(shí)現(xiàn)右下角彈出框
這篇文章主要為大家詳細(xì)介紹了python+pyqt實(shí)現(xiàn)右下角彈出框,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10Python日期和時間戳的轉(zhuǎn)換的實(shí)現(xiàn)方式
Python中日期和時間的處理涉及到time和datetime模塊,time模塊可實(shí)現(xiàn)時間戳與格式化時間字符串的轉(zhuǎn)換,而datetime模塊則提供更加直接易用的接口,本文詳細(xì)給大家介紹了Python日期和時間戳的轉(zhuǎn)換的實(shí)現(xiàn)方式,需要的朋友可以參考下2024-10-10Python logging設(shè)置和logger解析
這篇文章主要介紹了Python logging設(shè)置和logger解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08python神經(jīng)網(wǎng)絡(luò)VGG16模型復(fù)現(xiàn)及其如何預(yù)測詳解
這篇文章主要為大家介紹了VGG16模型的復(fù)現(xiàn)及其詳解(包含如何預(yù)測),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05