it编程 > 编程语言 > rust

探索ASGI:Python的Web应用程序异步协议

56人参与 2025-03-30 rust

探索asgi:python的web应用程序异步协议

leapcell:python web 托管、异步任务和 redis 的最佳无服务器平台

本文探讨 python web 应用中 asgi 协议与 uvicorn 服务器的关系。 初学者常疑惑为何 fastapi 开发需要 uvicorn,本文将解答此疑问。

uvicorn 的作用

以下是一个简单的 http 请求示例,使用 uvicorn 运行:

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 项目的理想平台:

探索asgi:python的web应用程序异步协议

了解更多信息,请访问 leapcell 文档和 twitter。

以上就是探索asgi:python的web应用程序异步协议的详细内容,更多请关注代码网其它相关文章!

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

什么是MANTRA (OM)币

03-30

Yandex 开发并开源 Perforator,这款开源工具每年可为企业节省数十亿美元的服务器基础设施成本

03-30

Golang环境深处潜水:从零到英雄

03-30

掌握Rollupjs:从基础到高级

03-30

哪个JavaScript Bundler适合您?深入了解Webpack,Vite等

03-30

腐蚀手游上线时间什么时候-腐蚀手游玩法是什么

03-30

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论