Pyscript中async函数使用await后代码无法执行求助
问题分析与解决方案
核心问题1:错误的no-cors模式设置
你在request函数里硬编码了"mode": "no-cors",这会导致浏览器强制限制请求的响应内容——即使你的API已经配置了正确的CORS策略,no-cors模式下response.json()根本无法读取响应体,而且这种错误不会抛出明确的异常,直接导致代码卡在await处,后续逻辑无法执行。
解决方法:删除"mode": "no-cors"这一行,浏览器会默认使用cors模式,匹配你API的CORS配置。
核心问题2:缺失异常捕获逻辑
异步任务中如果发生错误(比如请求失败、解析JSON出错),asyncio.ensure_future创建的任务会静默失败,不会输出任何错误信息,导致你看不到后续代码执行的原因。
解决方法:在异步函数中添加try-except块,捕获并打印异常,方便排查问题。
可选优化:PyScript中异步任务的启动方式
虽然asyncio.ensure_future可以运行异步任务,但在PyScript中更推荐使用asyncio.run(main()),或者如果你的<py-script>标签添加了async属性,直接在顶层使用await main(),这两种方式的错误处理更直观。
修改后的完整代码
from typing import Optional, Dict, Any from pyscript import pyfetch async def request(url: str, method: str = "GET", body: Optional[str] = None, headers: Optional[Dict[str, str]] = None, **fetch_kwargs: Any): kwargs = { "method": method } if body and method not in ["GET", "HEAD"]: kwargs["body"] = body if headers: kwargs["headers"] = headers kwargs.update(fetch_kwargs) response = await pyfetch(url, **kwargs) return response async def get_barycenter( filename: str, base_url: str = "http://localhost:8001") -> Dict[str, Any] | None: try: headers = {"Content-type": "application/json"} response = await request(f"{base_url}/barycenter/?image_name={filename}", headers=headers) # 先检查响应状态码 if not response.ok: print(f"API请求失败,状态码: {response.status}") return None body = await response.json() if body.get("status") != 200: print(f"API返回错误: {body.get('msg')}") return None return body.get("msg") except Exception as e: print(f"get_barycenter执行出错: {str(e)}") return None async def main(): try: print('start') test = await get_barycenter("img.jpg") print(test) print("end") except Exception as e: print(f"main执行出错: {str(e)}") # 使用asyncio.run替代ensure_future import asyncio asyncio.run(main())
内容的提问来源于stack exchange,提问作者Samuel Diop
相关产品推荐
相关产品推荐

