原文:https://lwebapp.com/zh/post/pyodide-fetch
需求
小編之前提過一個在線 Python 工具,核心技術(shù)是用到了一個叫 Pyodide 的庫,能夠讓 Python 在網(wǎng)頁上運行,但是小編在學(xué)習(xí)過程中發(fā)現(xiàn),并不是所有 Python 內(nèi)置庫或者擴展庫都能運行,比如 requests是不支持的。
根據(jù)這個 issue 下的討論,requests依賴于 Lib/http.client.py,后者依賴于 Lib/sockets.py,后者依賴于需要 <sys/socket.h> 的 socketmodule.c。 Emscripten 提供 <sys/socket.h> 支持,但如果我們使用它,那么 http 請求只有在我們將它們與接受 WebSocket 的自定義服務(wù)器一起使用時才會起作用(或通過可以轉(zhuǎn)發(fā)請求的此類服務(wù)器代理所有請求) 作為真正的 http 請求,這個設(shè)計不太理想。
所以如果你的本地 Python 程序用到了requests的方法,轉(zhuǎn)換到我們的在線 Python 工具運行的時候,是需要更新網(wǎng)絡(luò)請求的用法。這里我們簡要介紹下 3 種網(wǎng)絡(luò)請求的方法。
方法
1. http.open_url
同步獲取給定的 URL 請求數(shù)據(jù)
import pyodide
print(pyodide.http.open_url('https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8').read())
在線 Demo: Python Playground - http.open_url
2. http.pyfetch
獲取 url 并返回響應(yīng)
import pyodide
async def get_data():
response = await pyodide.http.pyfetch('https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8')
data = await response.json()
print(data)
get_data()
在線 Demo: Python Playground - http.pyfetch
獲取圖片數(shù)據(jù)推薦用此方法
# 請求圖片
response = await pyodide.http.pyfetch('https://gcore.jsdelivr.net/gh/openHacking/static-files@main/img/16576149784751657614977527.png')
# 將響應(yīng)正文作為字節(jié)對象返回
image_data = await response.bytes()
詳細參考案例:網(wǎng)頁版 Python 圖片轉(zhuǎn)字符畫
3. js 模塊中的 fetch
Pyodide 包裝了 js API,使用原生 js 的 fetch API 即可實現(xiàn)網(wǎng)絡(luò)請求
import json
from js import fetch,JSON
async def get_data():
response = await fetch('https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8',{'method':'GET'})
data = await response.json()
print(JSON.stringify(data))
await get_data()
在線 Demo: Python Playground - js fetch
總結(jié)
以上就是我總結(jié)的在 Pyodide 中常用的 3 種網(wǎng)絡(luò)請求方法,可能還有很多不足,如果你有更好的方法歡迎分享出來。