当前位置:网站首页>Pyodide 中实现网络请求的 3 种方法
Pyodide 中实现网络请求的 3 种方法
2022-07-17 09:46:00 【InfoQ】
原文:
https://lwebapp.com/zh/post/pyodide-fetch
需求
小编之前提过一个
在线 Python 工具
,核心技术是用到了一个叫
Pyodide
的库,能够让 Python 在网页上运行,但是小编在学习过程中发现,并不是所有 Python 内置库或者扩展库都能运行,比如
requests是不支持的。
根据这个
issue
下的讨论,
requests依赖于
Lib/http.client.py,后者依赖于
Lib/sockets.py,后者依赖于需要
<sys/socket.h> 的
socketmodule.c。 Emscripten 提供
<sys/socket.h> 支持,但如果我们使用它,那么 http 请求只有在我们将它们与接受 WebSocket 的自定义服务器一起使用时才会起作用(或通过可以转发请求的此类服务器代理所有请求) 作为真正的 http 请求,这个设计不太理想。
所以如果你的本地 Python 程序用到了
requests的方法,转换到我们的在线 Python 工具运行的时候,是需要更新网络请求的用法。这里我们简要介绍下 3 种网络请求的方法。
方法
1. http.open_url
同步获取给定的 URL 请求数据
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 并返回响应
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
获取图片数据推荐用此方法
# 请求图片
response = await pyodide.http.pyfetch('https://gcore.jsdelivr.net/gh/openHacking/[email protected]/img/16576149784751657614977527.png')
# 将响应正文作为字节对象返回
image_data = await response.bytes()
详细参考案例:
网页版 Python 图片转字符画
3. js 模块中的 fetch
Pyodide 包装了 js API,使用原生 js 的 fetch API 即可实现网络请求
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
总结
以上就是我总结的在 Pyodide 中常用的 3 种网络请求方法,可能还有很多不足,如果你有更好的方法欢迎分享出来。
参考
- Pyodide 中实现网络请求的 3 种方法
- pyodide python api
- pyodide.http.open_url
- pyodide.http.pyfetch
- pyodide.runPythonAsync
- pyodide - requests module is not available #398
边栏推荐
- Markdown(5):锚链接
- Towhee daily model weekly report
- MySQL 视图
- 小说里的编程 【连载之十一】元宇宙里月亮弯弯
- Microservice splitting for stand-alone projects
- 二、品达通用权限系统__项目搭建
- Use < pre > and json Stringify handles the format of web page presentation JSON
- mysql 初始化修改密码问题
- MySQL索引(三)
- Programming in the novel [serial 13] the moon bends in the yuan universe
猜你喜欢
随机推荐
SDL图像显示
Etcd database source code analysis -- etcdserver bootstrap recover store from snapshot
MySQL索引(一)
Two structures ifconf and ifreq
数据库——sql-server
MySQL索引(二)
Towhee 每日模型周报
pygame中display模块
【Flink】Flink 设置检查点失败一次就报错 setTolerableCheckpointFailureNumber 不起作用
Daily model series: July 11, 2022
Jsp+Ajax+Servlet+Mysql实现增删改查(一)
[troubleshooting] common problems and solutions when installing MySQL in Windows system
单机项目进行微服务拆分
KNN分类器
Cocos shader basics 7
Programming in the novel [serial 15] the moon bends in the yuan universe
Left connection query of Android database
Shell notes
shell-笔记
Towhee daily model weekly report









