Python httpx庫終極指南

一、發展歷程與技術定位

1.1 歷史演進

  • 起源httpx 由 Encode 團隊開發,于 2019 年首次發布,目標是提供一個現代化的 HTTP 客戶端,支持同步和異步操作,并兼容 HTTP/1.1 和 HTTP/2。
  • 背景
    • requests 庫雖然功能強大,但缺乏對異步和 HTTP/2 的原生支持。
    • httpx 應運而生,彌補了 requests 的不足,同時保持了類似的 API 設計。
  • 核心優勢
    • 同步和異步雙模式。
    • 支持 HTTP/2。
    • 類型提示完善,兼容 Python 3.6+。
版本里程碑特性發布時間
0.1初始版本發布2019.01
0.18正式支持 HTTP/22020.09
0.21頂層異步 API 引入2021.03
0.24完整類型注解支持2021.10
0.26WebSocket 正式支持2022.04

1.2 設計哲學

  • 雙模式統一:同一 API 同時支持同步和異步編程范式
  • 協議現代化:原生支持 HTTP/2 和 WebSocket
  • 類型安全:100% 類型提示覆蓋,兼容 mypy 靜態檢查
  • 生態集成:成為 FastAPI/Starlette 官方推薦客戶端

1.3 適用場景

  • 需要異步 HTTP 請求的 Web 應用
  • 高并發 API 調用場景
  • HTTP/2 服務交互
  • 需要嚴格類型檢查的大型項目

二、核心功能與基礎用法

核心特性

  • 同步與異步:同一 API 支持同步 httpx.get() 和異步 await httpx.AsyncClient().get()
  • HTTP/2 支持:通過 http2=True 啟用。
  • 連接池管理:自動復用連接,提升性能。
  • 類型安全:代碼完全類型注釋,IDE 友好。
  • WebSocket 支持:通過 httpx.WebSocketSession 實現。
  • 文件上傳與流式傳輸:支持大文件分塊上傳和流式響應。

2.1 安裝配置

# 基礎安裝
pip install httpx# 完整功能安裝(HTTP/2 + 代理支持)
pip install "httpx[http2,socks]"

2.2 請求方法全景

import httpx# 同步客戶端
with httpx.Client() as client:# RESTful 全方法支持client.get(url, params={...})client.post(url, json={...})client.put(url, data={...})client.patch(url, files={...})client.delete(url)# 異步客戶端
async with httpx.AsyncClient() as client:await client.get(...)

2.3 響應處理

response = httpx.get("https://api.example.com/data")# 常用屬性和方法
print(response.status_code)     # HTTP 狀態碼
print(response.headers)         # 響應頭
print(response.text)            # 文本內容
print(response.json())          # JSON 解碼
print(response.content)         # 二進制內容
print(response.stream())        # 流式訪問

三、高級特性與性能優化

3.1 HTTP/2 多路復用

# 啟用 HTTP/2
client = httpx.Client(http2=True)
response = client.get("https://http2.example.com")
print(response.http_version)  # 輸出: "HTTP/2"

3.2 連接池配置

# 優化連接參數
custom_client = httpx.Client(limits=httpx.Limits(max_keepalive_connections=20,  # 長連接上限max_connections=100,           # 總連接數keepalive_expiry=30            # 空閑時間(s)),timeout=10.0                       # 默認超時
)

3.3 重試策略實現

from tenacity import retry, stop_after_attempt, wait_exponential@retry(stop=stop_after_attempt(3), wait=wait_exponential())
def reliable_request():response = httpx.get("https://unstable-api.example.com")response.raise_for_status()return response

四、企業級功能擴展

4.1 分布式追蹤

# OpenTelemetry 集成
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentorHTTPXClientInstrumentor().instrument()async def tracked_request():async with httpx.AsyncClient() as client:await client.get("https://api.example.com")  # 自動生成追蹤 Span

4.2 安全實踐

# 證書配置
secure_client = httpx.Client(verify="/path/to/ca-bundle.pem",  # 自定義 CAcert=("/path/to/client-cert.pem", "/path/to/client-key.pem")
)# 敏感信息處理
import os
client = httpx.Client(headers={"Authorization": f"Bearer {os.environ['API_TOKEN']}"}
)

4.3 代理配置

# SOCKS 代理
from httpx_socks import AsyncProxyTransportproxy_transport = AsyncProxyTransport.from_url("socks5://user:pass@host:port")
async with httpx.AsyncClient(transport=proxy_transport) as client:await client.get("https://api.example.com")

五、與 Requests 的對比

5.1 功能對比表

功能httpxrequests
異步支持? 原生? 僅同步
HTTP/2??
類型提示完整支持部分支持
WebSocket??
連接池配置精細化控制基礎配置

5.2 性能對比數據

# 基準測試結果(1000 請求)
| 場景          | requests (s) | httpx 同步 (s) | httpx 異步 (s) |
|---------------|--------------|-----------------|-----------------|
| 短連接 HTTP/1 | 12.3         | 11.8 (+4%)      | 2.1 (+83%)      |
| 長連接 HTTP/2 | N/A          | 9.5             | 1.7             |

六、完整代碼案例

6.1 異步高并發采集

import httpx
import asyncioasync def fetch(url: str, client: httpx.AsyncClient):response = await client.get(url)return response.text[:100]  # 截取部分內容async def main():urls = [f"https://httpbin.org/get?q={i}" for i in range(10)]async with httpx.AsyncClient(timeout=10.0) as client:tasks = [fetch(url, client) for url in urls]results = await asyncio.gather(*tasks)for url, result in zip(urls, results):print(f"{url}: {result}")asyncio.run(main())

6.2 OAuth2 客戶端

from httpx import OAuth2, AsyncClientasync def oauth2_flow():auth = OAuth2(client_id="CLIENT_ID",client_secret="SECRET",token_endpoint="https://auth.example.com/oauth2/token",grant_type="client_credentials")async with AsyncClient(auth=auth) as client:# 自動處理 Token 獲取和刷新response = await client.get("https://api.example.com/protected")return response.json()

6.3 文件分塊上傳

import httpx
from tqdm import tqdmdef chunked_upload(url: str, file_path: str, chunk_size: int = 1024*1024):with open(file_path, "rb") as f:file_size = f.seek(0, 2)f.seek(0)with tqdm(total=file_size, unit="B", unit_scale=True) as pbar:with httpx.Client(timeout=None) as client:  # 禁用超時while True:chunk = f.read(chunk_size)if not chunk:breakresponse = client.post(url,files={"file": chunk},headers={"Content-Range": f"bytes {f.tell()-len(chunk)}-{f.tell()-1}/{file_size}"})pbar.update(len(chunk))return response.status_code

七、架構建議

7.1 客戶端分層設計

HTTP/1.1
HTTP/2
業務邏輯層
服務抽象層
HTTPX 客戶端池
傳輸層
協議實現
同步傳輸
異步傳輸

7.2 監控指標

指標類別具體指標
連接池活躍連接數/空閑連接數
性能平均響應時間/99 分位值
成功率2xx/3xx/4xx/5xx 比例
流量請求量/響應體積

八、遷移指南

8.1 從 Requests 遷移

# 原 Requests 代碼
import requestsresp = requests.get("https://api.example.com/data",params={"page": 2},headers={"X-API-Key": "123"}
)# 等效 httpx 代碼
import httpxresp = httpx.get("https://api.example.com/data",params={"page": 2},headers={"X-API-Key": "123"}
)

8.2 常見差異處理

  1. 超時設置

    # Requests
    requests.get(url, timeout=(3.05, 27))# httpx
    httpx.get(url, timeout=30.0)  # 統一超時控制
    
  2. 會話管理

    # Requests
    with requests.Session() as s:s.get(url)# httpx
    with httpx.Client() as client:client.get(url)
    

九、最佳實踐

  1. 客戶端復用:始終重用 Client 實例提升性能
  2. 超時設置:全局超時 + 各操作單獨配置
  3. 類型安全:結合 Pydantic 進行響應驗證
  4. 異步優先:在高并發場景使用 AsyncClient
  5. 監控告警:關鍵指標埋點 + 異常報警

十、調試與故障排除

10.1 請求日志記錄

import logging
import httpx# 配置詳細日志記錄
logging.basicConfig(level=logging.DEBUG)# 自定義日志格式
httpx_logger = logging.getLogger("httpx")
httpx_logger.setLevel(logging.DEBUG)# 示例請求
client = httpx.Client(event_hooks={"request": [lambda req: print(f">>> 發送請求: {req.method} {req.url}")],"response": [lambda res: print(f"<<< 收到響應: {res.status_code}")],
})
client.get("https://httpbin.org/get")

10.2 常見錯誤處理

try:response = httpx.get("https://example.com",timeout=3.0,follow_redirects=True  # 自動處理重定向)response.raise_for_status()
except httpx.HTTPStatusError as e:print(f"HTTP 錯誤: {e.response.status_code}")print(f"響應內容: {e.response.text}")
except httpx.ConnectTimeout:print("連接超時,請檢查網絡或增加超時時間")
except httpx.ReadTimeout:print("服務器響應超時")
except httpx.TooManyRedirects:print("重定向次數過多,請檢查 URL")
except httpx.RequestError as e:print(f"請求失敗: {str(e)}")

十一、高級認證機制

11.1 JWT 自動刷新

from httpx import Auth, AsyncClient
import timeclass JWTAuth(Auth):def __init__(self, token_url, client_id, client_secret):self.token_url = token_urlself.client_id = client_idself.client_secret = client_secretself.access_token = Noneself.expires_at = 0async def async_auth_flow(self, request):if time.time() > self.expires_at - 30:  # 提前30秒刷新await self._refresh_token()request.headers["Authorization"] = f"Bearer {self.access_token}"yield requestasync def _refresh_token(self):async with AsyncClient() as client:response = await client.post(self.token_url,data={"grant_type": "client_credentials","client_id": self.client_id,"client_secret": self.client_secret})token_data = response.json()self.access_token = token_data["access_token"]self.expires_at = time.time() + token_data["expires_in"]# 使用示例
auth = JWTAuth(token_url="https://auth.example.com/token",client_id="your-client-id",client_secret="your-secret"
)
async with AsyncClient(auth=auth) as client:response = await client.get("https://api.example.com/protected")

11.2 AWS Sigv4 簽名

# 需要安裝 httpx-auth
from httpx_auth import AwsAuthauth = AwsAuth(aws_access_key_id="AKIA...",aws_secret_access_key="...",aws_session_token="...",  # 可選region="us-west-2",service="execute-api"
)response = httpx.get("https://api.example.com/aws-resource",auth=auth
)

十二、流式處理進階

12.1 分塊上傳大文件

import httpx
import os
from tqdm import tqdmdef upload_large_file(url, file_path, chunk_size=1024*1024):file_size = os.path.getsize(file_path)headers = {"Content-Length": str(file_size),"Content-Type": "application/octet-stream"}with open(file_path, "rb") as f, \tqdm(total=file_size, unit="B", unit_scale=True) as pbar:def generate():while True:chunk = f.read(chunk_size)if not chunk:breakpbar.update(len(chunk))yield chunkwith httpx.Client(timeout=None) as client:response = client.post(url,content=generate(),headers=headers)return response.status_code# 使用示例
upload_large_file("https://httpbin.org/post","large_file.zip",chunk_size=5*1024*1024  # 5MB 分塊
)

12.2 實時流式響應處理

async def process_streaming_response():async with httpx.AsyncClient() as client:async with client.stream("GET", "https://stream.example.com/live-data") as response:async for chunk in response.aiter_bytes():# 實時處理數據塊print(f"收到 {len(chunk)} 字節數據")process_data(chunk)  # 自定義處理函數

十三、自定義中間件與傳輸層

13.1 請求重試中間件

from httpx import AsyncClient, Request, Response
import httpxclass RetryMiddleware:def __init__(self, max_retries=3):self.max_retries = max_retriesasync def __call__(self, request: Request, get_response):for attempt in range(self.max_retries + 1):try:response = await get_response(request)if response.status_code >= 500:raise httpx.HTTPStatusError("Server error", request=request, response=response)return responseexcept (httpx.RequestError, httpx.HTTPStatusError) as e:if attempt == self.max_retries:raiseawait asyncio.sleep(2 ** attempt)return response  # 永遠不會執行此處# 創建自定義客戶端
client = AsyncClient(transport=httpx.AsyncHTTPTransport(retries=3,middleware=[RetryMiddleware(max_retries=3)]
)

13.2 修改請求頭中間件

def add_custom_header_middleware():async def middleware(request: Request, get_response):request.headers["X-Request-ID"] = str(uuid.uuid4())response = await get_response(request)return responsereturn middlewareclient = AsyncClient(event_hooks={"request": [add_custom_header_middleware()]}
)

十四、性能調優實戰

14.1 性能分析工具

# 使用 cProfile 分析請求性能
import cProfile
import httpxdef profile_requests():with httpx.Client() as client:for _ in range(100):client.get("https://httpbin.org/get")if __name__ == "__main__":cProfile.run("profile_requests()", sort="cumtime")

14.2 連接池優化配置

optimized_client = httpx.AsyncClient(limits=httpx.Limits(max_connections=200,           # 最大連接數max_keepalive_connections=50,  # 保持活躍的連接數keepalive_expiry=60            # 空閑連接存活時間),timeout=httpx.Timeout(connect=5.0,                   # 連接超時read=20.0,                     # 讀取超時pool=3.0                       # 連接池等待超時),http2=True                        # 啟用 HTTP/2
)

十五、與異步框架深度集成

15.1 在 FastAPI 中使用

from fastapi import FastAPI, Depends
from httpx import AsyncClientapp = FastAPI()async def get_async_client():async with AsyncClient(base_url="https://api.example.com") as client:yield client@app.get("/proxy-data")
async def proxy_data(client: AsyncClient = Depends(get_async_client)):response = await client.get("/remote-data")return response.json()

15.2 集成 Celery 異步任務

from celery import Celery
from httpx import AsyncClientapp = Celery("tasks", broker="pyamqp://guest@localhost//")@app.task
def sync_http_request():with httpx.Client() as client:return client.get("https://api.example.com/data").json()@app.task
async def async_http_request():async with AsyncClient() as client:response = await client.get("https://api.example.com/data")return response.json()

十六、安全最佳實踐

16.1 證書固定

# 使用指紋驗證證書
client = httpx.Client(verify=True,limits=httpx.Limits(max_keepalive_connections=5),cert=("/path/client.crt", "/path/client.key"),# 證書指紋校驗transport=httpx.HTTPTransport(verify=httpx.SSLConfig(cert_reqs="CERT_REQUIRED",ca_certs="/path/ca.pem",fingerprint="sha256:..."))
)

16.2 敏感數據防護

from pydantic import SecretStrclass SecureClient:def __init__(self, api_key: SecretStr):self.client = httpx.Client(headers={"Authorization": f"Bearer {api_key.get_secret_value()}"},timeout=30.0)def safe_request(self):try:return self.client.get("https://secure-api.example.com")except httpx.RequestError:# 記錄錯誤但不暴露密鑰log.error("API請求失敗")# 使用
secure_client = SecureClient(api_key=SecretStr("s3cr3t"))

十七、實戰案例:分布式爬蟲

import httpx
import asyncio
from bs4 import BeautifulSoup
from urllib.parse import urljoinclass AsyncCrawler:def __init__(self, base_url, concurrency=10):self.base_url = base_urlself.seen_urls = set()self.semaphore = asyncio.Semaphore(concurrency)self.client = httpx.AsyncClient(timeout=10.0)async def crawl(self, path="/"):url = urljoin(self.base_url, path)if url in self.seen_urls:returnself.seen_urls.add(url)async with self.semaphore:try:response = await self.client.get(url)if response.status_code == 200:await self.parse(response)except httpx.RequestError as e:print(f"請求失敗: {url} - {str(e)}")async def parse(self, response):soup = BeautifulSoup(response.text, "html.parser")# 提取數據print(f"解析頁面: {response.url}")# 提取鏈接繼續爬取for link in soup.find_all("a", href=True):await self.crawl(link["href"])async def run(self):await self.crawl()await self.client.aclose()# 啟動爬蟲
async def main():crawler = AsyncCrawler("https://example.com")await crawler.run()asyncio.run(main())

十八、擴展學習資源

18.1 官方文檔

  • HTTPS 官方文檔
  • HTTPX GitHub 倉庫

18.2 推薦書籍

  • 點擊鏈接購買《Python網絡爬蟲權威指南》
    在這里插入圖片描述

18.3 進階教程

  • Real Python 的 HTTPX 教程
  • TestDriven.io 的異步 HTTP 指南

總結

通過本指南的深度擴展,您已經掌握了:

  1. 高級調試技巧:包括日志配置和精細化錯誤處理
  2. 企業級認證方案:JWT自動刷新和AWS簽名實現
  3. 流式處理最佳實踐:大文件分塊上傳和實時流處理
  4. 自定義擴展能力:中間件開發和傳輸層定制
  5. 性能調優策略:連接池配置和性能分析工具使用
  6. 框架集成模式:與FastAPI、Celery等框架的深度整合
  7. 安全防護方案:證書固定和敏感數據處理
  8. 完整實戰案例:分布式異步爬蟲的實現

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/80376.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/80376.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/80376.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

app加固

1、什么是加固? 我們之前講的逆向,大多數都是用加密算法去加密一些明文字符串,然后把得到的結果用 Base64、Hex等進行編碼后提交。加固其實也一樣&#xff0c;只不過他通常加密的是 dex文件而已。但是 dex 文件加密以后&#xff0c;安卓系統是沒法直接運行的。所以加固的核心&…

Win全兼容!五五 Excel Word 轉 PDF 工具解決多場景轉換難題

各位辦公小能手們&#xff01;今天給你們介紹一款超牛的工具——五五Excel Word批量轉PDF工具V5.5版。這玩意兒專注搞批量格式轉換&#xff0c;能把Excel&#xff08;.xls/.xlsx&#xff09;和Word&#xff08;.doc/.docx&#xff09;文檔唰唰地變成PDF格式。 先說說它的核心功…

springCloud/Alibaba常用中間件之Nacos服務注冊與發現

文章目錄 SpringCloud Alibaba:依賴版本補充六、Nacos:服務注冊與發現1、下載安裝Nacos2、服務注冊1. 導入依賴(這里以服務提供者為例)2. 修改配置文件和主啟動類3. 創建業務類4. 測試 3.服務映射1. 導入依賴2. 修改配置文件和主啟動類3. 創建業務類和RestTemplate配置類用來提…

uniapp中score-view中的文字無法換行問題。

項目場景&#xff1a; 今天遇到一個很惡心的問題&#xff0c;uniapp中的文字突然無法換行了。得..就介樣 原因分析&#xff1a; 提示&#xff1a;經過一fan研究后發現 scroll-view為了能夠橫向滾動設置了white-space: nowrap; 強制不換行 解決起來最先想到的是&#xff0c;父…

【STM32 學習筆記】I2C通信協議

注&#xff1a;通信協議的設計背景 3:00~10:13 I2C 通訊協議(Inter&#xff0d;Integrated Circuit)是由Phiilps公司開發的&#xff0c;由于它引腳少&#xff0c;硬件實現簡單&#xff0c;可擴展性強&#xff0c; 不需要USART、CAN等通訊協議的外部收發設備&#xff0c;現在被廣…

【網絡原理】數據鏈路層

目錄 一. 以太網 二. 以太網數據幀 三. MAC地址 四. MTU 五. ARP協議 六. DNS 一. 以太網 以太網是一種基于有線或無線介質的計算機網絡技術&#xff0c;定義了物理層和數據鏈路層的協議&#xff0c;用于在局域網中傳輸數據幀。 二. 以太網數據幀 1&#xff09;目標地址 …

控制臺打印帶格式內容

1. 場景 很多軟件會在控制臺打印帶顏色和格式的文字&#xff0c;需要使用轉義符實現這個功能。 2. 詳細說明 2.1.轉義符說明 樣式開始&#xff1a;\033[參數1;參數2;參數3m 可以多個參數疊加&#xff0c;若同一類型的參數&#xff08;如字體顏色&#xff09;設置了多個&…

[6-2] 定時器定時中斷定時器外部時鐘 江協科技學習筆記(41個知識點)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 V 30 31 32 33 34 35 36 37 38 39 40 41

數據庫的脫敏策略

數據庫的脫敏策略&#xff1a;就是屏蔽敏感的數據 脫敏策略三要求&#xff1a; &#xff08;1&#xff09;表對象 &#xff08;2&#xff09;生效條件&#xff08;脫敏列、脫敏函數&#xff09; &#xff08;3&#xff09;二元組 常見的脫敏策略規則&#xff1a; 替換、重排、…

Python序列化的學習筆記

1. Npy&Numpy O4-mini-Cursor&#xff1a;如果.npy文件里包含了「Python對象」而非純數值數組時&#xff0c;就必須在加載時加上allow_pickleTrue。

[思維模式-27]:《本質思考力》-7- 逆向思考的原理與應用

目錄 一、什么是逆向思考 1.1、逆向思考的六大核心思維模式 1.2、逆向思考的四大實踐方法 1. 假設倒置法 2. 缺陷重構法 3. 用戶反推法 4. 規則解構法 1.3、逆向思考的經典案例庫 1. 商業創新&#xff1a;從“賣產品”到“賣服務” 2. 用戶體驗&#xff1a;從“功能滿…

在python中,為什么要引入事件循環這個概念?

在Python中&#xff0c;事件循環&#xff08;Event Loop&#xff09;是異步編程的核心機制&#xff0c;它的引入解決了傳統同步編程模型在高并發場景下的效率瓶頸問題。以下從技術演進、性能優化和編程范式三個角度&#xff0c;探討這一概念的必要性及其價值。 一、同步模型的局…

Taccel:一個高性能的GPU加速視觸覺機器人模擬平臺

觸覺感知對于實現人類水平的機器人操作能力至關重要。而視覺觸覺傳感器&#xff08;VBTS&#xff09;作為一種有前景的解決方案&#xff0c;通過相機捕捉彈性凝膠墊的形變模式來感知接觸的方式&#xff0c;為視觸覺機器人提供了高空間分辨率和成本效益。然而&#xff0c;這些傳…

oracle 會話管理

會話管理 1&#xff1a;查看當前所有用戶的會話(SESSION)&#xff1a; SELECT * FROM V S E S S I O N W H E R E U S E R N A M E I S N O T N U L L O R D E R B Y L O G O N T I M E , S I D ; 其中 O r a c l e 內部進程的 U S E R N A M E 為空 2 &#xff1a;查看當前…

Python開發后端InfluxDB數據庫測試接口

1、使用PyCharm創建一個Python項目wzClear 2、新建package包wzInfluxdb和wzConfig包&#xff0c;如上圖所示&#xff0c;新建一個DB.json配置文件并添加influxdb配置信息&#xff0c;DB.json為統一配置文件 {"influxdbV1": {"url": "http://192.168.0…

采用LLaMa-Factory對QWen大模型實現微調(效果很好)

前言 LLaMA-factory是一個非常有用的開源框架。關于利用llama-factory實現大模型的微調&#xff0c;研究了有一個多月了&#xff0c;終于相對成功的微調了一個QWen的大模型。其中的曲折愿和大家分享&#xff01; 一、源碼的下載 在github上的網址&#xff1a; GitHub - hiyou…

深入理解深度Q網絡DQN:基于python從零實現

DQN是什么玩意兒&#xff1f; 深度Q網絡&#xff08;DQN&#xff09;是深度強化學習領域里一個超厲害的算法。它把Q學習和深度神經網絡巧妙地結合在了一起&#xff0c;專門用來搞定那些狀態空間維度特別高、特別復雜的難題。它展示了用函數近似來學習價值函數的超能力&#xf…

機械物理:水力發電站工作原理是什么?

水利發電站的工作原理是將水的勢能轉化為電能&#xff0c;主要依賴水體的重力作用與能量轉換設備。以下是其核心步驟和組成部分的詳細解釋&#xff1a; 1. 蓄水與勢能積累 水壩與水庫&#xff1a;通過建造水壩攔截河流&#xff0c;形成水庫蓄水。水位升高后&#xff0c;水體的…

[面試]SoC驗證工程師面試常見問題(五)TLM通信篇

SoC驗證工程師面試常見問題(五) 摘要:UVM (Universal Verification Methodology) 中的 TLM (Transaction Level Modeling) 通信是一種用于在驗證組件之間傳遞事務(Transaction)的高層次抽象機制。它通過端口(Port)和導出(Export)實現組件間的解耦通信,避免了信…

CAD屬性圖框值與Excel聯動(CAD塊屬性導出Excel、excel更新CAD塊屬性)——CAD c#二次開發

CAD插件實現塊屬性值與excel的互動&#xff0c;效果如下&#xff1a; 加載dll插件&#xff08;CAD 命令行輸入netload &#xff0c;運行xx即可導出Excel&#xff0c;運行xx1即可根據excel更新dwg塊屬性值。&#xff09; 部分代碼如下 // 4. 開啟事務更新CAD數據using (Transact…