惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hacker News: Ask HN
Hacker News: Ask HN
Recent Commits to openclaw:main
Recent Commits to openclaw:main
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
Check Point Blog
S
Security Affairs
Hacker News - Newest:
Hacker News - Newest: "LLM"
S
Secure Thoughts
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
T
The Blog of Author Tim Ferriss
B
Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Google DeepMind News
Google DeepMind News
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
A
Arctic Wolf
T
The Exploit Database - CXSecurity.com
Stack Overflow Blog
Stack Overflow Blog
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
AWS News Blog
AWS News Blog
MongoDB | Blog
MongoDB | Blog
Y
Y Combinator Blog
Google Online Security Blog
Google Online Security Blog
T
Troy Hunt's Blog
I
InfoQ
L
LINUX DO - 热门话题
WordPress大学
WordPress大学
C
Cisco Blogs
G
GRAHAM CLULEY
The Register - Security
The Register - Security
A
About on SuperTechFans
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Schneier on Security
Schneier on Security
Project Zero
Project Zero
H
Hackread – Cybersecurity News, Data Breaches, AI and More
P
Privacy & Cybersecurity Law Blog
Cloudbric
Cloudbric
H
Hacker News: Front Page
小众软件
小众软件
雷峰网
雷峰网
The Hacker News
The Hacker News
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
Tor Project blog
博客园 - 聂微东
N
Netflix TechBlog - Medium
V
Vulnerabilities – Threatpost
The GitHub Blog
The GitHub Blog
腾讯CDC
P
Palo Alto Networks Blog
Scott Helme
Scott Helme

博客园 - Sanny.Liu-CV&&ML

GRPO 是否“真的在学” clip的底层原理---深入源码:手把手剖析OpenAI CLIP的实现结构与细节 Decoder-Only、Encoder-Only 与 Encoder-Decoder linux 进程内存占用查看 算一个bbox和一个mask区域的重叠 用PyTorch从零搭建一个Transformer模型 基于树编辑距离的相似度(TEDS) 图片,二进制,base64互转 OCR相关的笔记 opencv的RGB 颜色表 transformers中的generate函数解读 5 levels of text splitting PyMuPDF工具说明 OCR表格识别 stable diffusion中controlnet详细使用方法总结 lora训练参数设置 Dreambooth, Textual Inversion, LoRA, Hypernetworks ,示意图解释 转载:深度学习:蒸馏Distill MoveNet:超快且准确的姿态检测模型 根据5个人脸特征点,快速计算人脸角度
uvicorn,一个无敌的 Python 库!
Sanny.Liu-CV&&ML · 2024-05-14 · via 博客园 - Sanny.Liu-CV&&ML

转载:https://zhuanlan.zhihu.com/p/682326316

大家好,今天为大家分享一个无敌的 Python 库 - uvicorn。

Github地址:https://github.com/encode/uvicorn


Python Uvicorn 是一个快速的 ASGI(Asynchronous Server Gateway Interface)服务器,用于构建异步 Web 服务。它基于 asyncio 库,支持高性能的异步请求处理,适用于各种类型的 Web 应用程序。本文将介绍 Uvicorn 的基本概念、使用方法以及一些实际示例,帮助快速上手构建异步 Web 服务。

更多Python学习内容:http://ipengtao.com

什么是 Uvicorn?

Uvicorn 是由 Starlette 框架的作者编写的 ASGI 服务器,旨在提供高性能的异步请求处理能力。它使用 asyncio 库实现异步 I/O 操作,支持 HTTP 和 WebSocket 协议,可与各种 ASGI 应用程序框架(如 FastAPI、Django、Starlette 等)配合使用。

安装 Uvicorn

可以使用 pip 包管理工具来安装 Uvicorn:

安装完成后,就可以在命令行中使用 uvicorn 命令了。

使用示例

下面是一个简单的示例,演示了如何使用 Uvicorn 启动一个异步 Web 服务:

# main.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello, World!"}

保存以上代码到 main.py 文件中。然后,在命令行中执行以下命令:

uvicorn main:app --reload

这将启动一个名为 main 的 ASGI 应用程序,使用 Uvicorn 服务器运行在本地主机的默认端口 8000 上,并监听根路径 / 的 GET 请求。在浏览器中访问 http://localhost:8000,将看到 "Hello, World!" 的消息。

配置选项

Uvicorn 提供了丰富的配置选项,以满足不同需求。可以通过命令行参数或配置文件来配置 Uvicorn 的行为。

以下是一些常用的配置选项:

  • --host:指定主机地址,默认为 127.0.0.1
  • --port:指定端口号,默认为 8000
  • --workers:指定工作进程数量,默认为 CPU 核心数的 1 倍。
  • --log-level:指定日志级别,默认为 info
  • --reload:在代码修改时自动重新加载应用程序。

高级功能

在本节中,更深入地探讨 Python Uvicorn 的高级功能,并提供丰富的示例代码。

1 SSL 支持

Uvicorn 支持通过 SSL 加密来提供安全的通信。可以使用 --ssl-keyfile 和 --ssl-certfile 参数来指定 SSL 密钥文件和证书文件。

uvicorn main:app --ssl-keyfile key.pem --ssl-certfile cert.pem

2 WebSocket 支持

除了处理 HTTP 请求外,Uvicorn 还支持处理 WebSocket 连接,用于实时通信应用程序。可以在 FastAPI 中使用 WebSocket 类来处理 WebSocket 连接。

# websocket_app.py

from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message text was: {data}")

3 中间件

Uvicorn 支持使用中间件来修改请求和响应,以及执行其他自定义操作。可以通过 --middleware 参数来指定中间件。

# middleware.py

from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
from uvicorn.middleware.debug import DebugMiddleware
from fastapi import FastAPI

app = FastAPI()

app.add_middleware(ProxyHeadersMiddleware, trusted_hosts=["10.0.0.1"])
app.add_middleware(DebugMiddleware)

@app.get("/")
async def read_root():
    return {"message": "Hello, World!"}

4 异步任务

Uvicorn 支持在异步 Web 服务中执行异步任务。可以在 FastAPI 应用程序中定义异步函数,并在其中执行耗时操作,而不会阻塞主事件循环。

# async_task.py

from fastapi import FastAPI
import asyncio

app = FastAPI()

async def background_task():
    while True:
        print("Background task is running...")
        await asyncio.sleep(5)

@app.on_event("startup")
async def startup_event():
    asyncio.create_task(background_task())

@app.get("/")
async def read_root():
    return {"message": "Hello, World!"}

5 自定义错误处理

可以通过自定义异常处理器来处理异常情况,如未找到页面、服务器错误等。

# error_handling.py

from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id == 42:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item_id": item_id}

实际应用场景

1 异步 API 服务

使用 Uvicorn 可以轻松构建异步 API 服务,处理大量并发请求,提高系统的性能和吞吐量。

# async_api.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

2 Websocket 服务

Uvicorn 支持 WebSocket 协议,可以使用它来构建实时通信的 Web 应用程序。

# websocket_server.py

import asyncio
import websockets

async def echo(websocket, path):
    async for message in websocket:
        await websocket.send(message)

start_server = websockets.serve(echo, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

总结

通过本文的介绍,了解了如何使用 Python Uvicorn 构建异步 Web 服务。学会了安装 Uvicorn、启动简单的 Web 应用程序、配置 Uvicorn 的行为、使用高级功能和处理实际应用场景。现在,可以开始使用 Uvicorn 构建自己的异步 Web 服务了!

更多Python学习内容:http://ipengtao.com