LeapCell:Python Web 托管、异步任务和 Redis 的最佳无服务器平台
本文探讨 Python Web 应用中 ASGI 协议与 Uvicorn 服务器的关系。 初学者常疑惑为何 FastAPI 开发需要 Uvicorn,本文将解答此疑问。
Uvicorn 的作用
以下是一个简单的 HTTP 请求示例,使用 Uvicorn 运行:
立即学习“Python免费学习笔记(深入)”;
import json def convert_bytes_to_str(data): if isinstance(data, bytes): return data.decode('utf-8') if isinstance(data, tuple): return tuple(convert_bytes_to_str(item) for item in data) if isinstance(data, list): return [convert_bytes_to_str(item) for item in data] if isinstance(data, dict): return {key: convert_bytes_to_str(value) for key, value in data.items()} return data async def app(scope, receive, send): data = convert_bytes_to_str(scope) print(json.dumps(data, indent=4)) if scope['type'] == 'http': event = await receive() response_body = json.dumps({"message": "hello, ASGI!"}).encode('utf-8') await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ (b'content-type', b'application/json'), ], }) await send({ 'type': 'http.response.body', 'body': response_body, })
convert_bytes_to_str 函数用于处理范围字段中的二进制字符串。 代码接收请求,创建 JSON 响应,并分两步发送响应头和响应体,这是异步编程的典型模式,提高了效率和对不同协议的兼容性。
ASGI (异步服务器网关接口)
ASGI 是构建异步 Python Web 应用的协议,其主要特点包括:
ASGI 协议主要由应用程序接口和服务器接口构成,并依赖于事件循环接口来调度异步任务。 ASGI 事件驱动模型管理应用生命周期、HTTP 请求处理和 WebSocket 连接。
Uvicorn 和应用层框架
Uvicorn 实现 ASGI 服务器层,但其应用层不够友好。 因此,出现了更高层的框架,例如 Starlette 和 FastAPI。 Uvicorn 需要一个 ASGI 应用实例,这些框架提供了这样的实例。 使用 Uvicorn 启动应用:
uvicorn main:app --reload
总结
本文阐述了 Uvicorn 在 Python Web ASGI 协议中的作用。 ASGI 赋予 Python Web 应用异步、并发和多协议处理能力。
LeapCell:最佳无服务器平台
最后,推荐 LeapCell 作为部署 Python 项目的理想平台:
了解更多信息,请访问 LeapCell 文档和 Twitter。
以上就是探索ASGI:Python的Web应用程序异步协议的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号