快速了解FastAPI与Uvicorn是什么?

概念

什么是Uvicorn

Python Uvicorn 是一个快速的 ASGI(Asynchronous Server Gateway Interface)服务器,用于构建异步 Web 服务。它基于 asyncio 库,支持高性能的异步请求处理,适用于各种类型的 Web 应用程序。

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

  • Uvicorn is an ASGI web server implementation for Python. Uvicorn
  • supports HTTP/1.1 and WebSockets.

源码地址: uvicorn
在这里插入图片描述

安装命令

pip install "uvicorn[standard]"

安装的是uvicorn-0.29.0

配置选项

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

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

查看帮助命令:

uvicorn --help

什么是FastAPI

在这里插入图片描述
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints.

The key features are:

  • Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available.
  • Fast to code: Increase the speed to develop features by about 200% to 300%. *
  • Fewer bugs: Reduce about 40% of human (developer) induced errors. *
  • Intuitive: Great editor support. Completion everywhere. Less time debugging.
  • Easy: Designed to be easy to use and learn. Less time reading docs.
  • Short: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
  • Robust: Get production-ready code. With automatic interactive documentation.
  • Standards-based: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.

* estimation based on tests on an internal development team, building production applications.

安装命令

pip install fastapi==0.110.1

示例

同步http服务

源代码

from typing import Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float
    is_offer: Union[bool, None] = None

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

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]

@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip: skip + limit]

@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}

@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    return {"item_name": item.name, "item_id": item_id}

启动命令

web1中python文件的名称web1.py

uvicorn web1:app --reload

输出如下:
在这里插入图片描述

查看swagger

  • http://127.0.0.1:8000/docs: 自动交互API文档(由Swagger UI提供)
  • http://127.0.0.1:8000/redoc:备选自动文档(由 ReDoc提供)

在这里插入图片描述
在这里插入图片描述

异步http服务

  • asynccontextmanager

源代码

import asyncio
from asyncio import Queue
from contextlib import asynccontextmanager
from dataclasses import dataclass
from random import randint
from uuid import UUID, uuid1

import uvicorn
from fastapi import FastAPI

async def commandA(queue: Queue):
    while True:
        print("Start to get task from a_queue")
        user_request: UserRequest = await queue.get()
        print(f"Got the task from the a_queue and guess will process {str(user_request.process_time)} seconds")
        await asyncio.sleep(user_request.process_time)
        queue.task_done()
        print(f"Completed task, task type is {user_request.type}, task id is {user_request.tracking_id}")

async def commandB(queue: Queue):
    while True:
        print("Start to get task from b_queue")
        user_request: UserRequest = await queue.get()
        await asyncio.sleep(user_request.process_time)
        print(f"Got the task from the b_queue and guess will process {str(user_request.process_time)} seconds")
        queue.task_done()
        print(f"Completed task, task type is {user_request.type}, task id is {user_request.tracking_id}")

async def commandC(queue: Queue):
    while True:
        print("Start to get task from c_queue")
        user_request: UserRequest = await queue.get()
        await asyncio.sleep(user_request.process_time)
        print(f"Got the task from the c_queue and guess will process {str(user_request.process_time)} seconds")
        queue.task_done()
        print(f"Completed task, task type is {user_request.type}, task id is {user_request.tracking_id}")

@asynccontextmanager
async def lifespan(app: FastAPI):
    asyncio.create_task(commandA(a_queue))
    asyncio.create_task(commandB(b_queue))
    asyncio.create_task(commandC(c_queue))
    yield

app = FastAPI(lifespan=lifespan)
# app = FastAPI()

a_queue = Queue()
b_queue = Queue()
c_queue = Queue()

@dataclass
class RequestBody:
    type: str

@dataclass
class UserRequest:
    tracking_id: UUID
    # A,B,C
    type: str = ""
    process_time: int = None

@app.post("/")
async def post_task(reqeust_body: RequestBody):
    user_request = UserRequest(
        tracking_id=uuid1(),
        type=reqeust_body.type,
        process_time=randint(1, 5)
    )
    # put requests to queue
    if user_request.type == "A":
        await a_queue.put(user_request)
    elif user_request.type == "B":
        await b_queue.put(user_request)
    elif user_request.type == "C":
        await c_queue.put(user_request)

    print(f"Received task, task type is {user_request.type}, task id is {user_request.tracking_id}")
    return "Received your request"


# @app.on_event("startup")
# def start_command_listener():
#     asyncio.create_task(commandA(a_queue))
#     asyncio.create_task(commandB(b_queue))
#     asyncio.create_task(commandC(c_queue))

if __name__ == "__main__":
    uvicorn.run(app=app, port=9000)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/521714.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

SEO超级外链工具源码

源码简介 超级外链工具,是一款在线全自动化发外链的推广工具。使用本工具可免费为网站在线批量增加外链,大大提高外链发布工作效率,是广大草根站长们必备的站长工具。 搭建环境 PHP 5.6 安装教程 上传源码压缩包到网站目录并解压即可 首…

Linux安装最新版Docker完整教程

参考官网地址:Install Docker Engine on CentOS | Docker Docs 一、安装前准备工作 1.1 查看服务器系统版本以及内核版本 cat /etc/redhat-release1.2 查看服务器内核版本 uname -r这里我们使用的是CentOS 7.6 系统,内核版本为3.10 1.3 安装依赖包 …

【数据结构(二)】顺序表与ArrayList

❣博主主页: 33的博客❣ ▶文章专栏分类:数据结构◀ 🚚我的代码仓库: 33的代码仓库🚚 🫵🫵🫵关注我带你学更多数据结构知识 目录 1.前言2.定义IList接口3.MyArraylist实现接口3.1定义成员变量与构造方法3.2添加元素3.3…

构建未来数字化世界的统一用户中心产品架构

随着数字化时代的到来,用户数据管理变得愈发复杂,各类应用和服务的涌现使得用户信息分散存储,导致了数据孤岛和体验碎片化的问题。在这样的背景下,统一用户中心产品架构应运而生,为构建数字化世界提供了全新的解决方案…

S7-200 SMART 应用第003期-数字量输入模块接线

概述 S7-200 SMART作为西门子的一款高性价比PLC产品,很多工控电气工程师在选型和电路图设计时,对模块接线并不是非常清楚,为了使大家更好的了解和掌握该部分,本文从CPU本体、数字量输入(DI)、数字量输出(DQ)向大家详细介绍S7-200 SMART 详细的接线和注意事项。 不同型号C…

2023年度总结:允许迷茫,破除迷茫;专注自身,把握当下

0、前言 📜为什么24年已经过了几个月,才提笔写这年度总结呢?毫不羞愧直问我的内心,其实就是懒罢了。直到前几天朋友看到了我去年写的总结,我自己点进那篇总结,完完整整的看了一遍,又翻看我23年…

ideaSSM 网上选课管理系统bootstrap开发mysql数据库web结构java编程计算机网页源码maven项目

一、源码特点 idea 开发 SSM 网上选课管理系统是一套完善的信息管理系统,结合SSM框架和bootstrap完成本系统,对理解JSP java编程开发语言有帮助系统采用SSM框架(MVC模式开发),系统具有完整的源代码和数据库&#xff…

二分法题集1

1 二分查找 分析: 这是一道很简单的二分法题,定义两个指针和中间值middle,判断middle对应数组值与目标值的大小关系,从而对left和right进行修改。由于太过基础,代码简单基础就不多赘述。 目录 1 二分查找 分析&…

PyQt PySide6零基础入门与项目实战视频教程

目录 课程亮点课程大纲第一章:基础篇 PySide6开发环境安装第二章 控件与布局篇 PySide6常用控件与界面布局使用介绍第三章 信号槽与事件机制第四章 QMainWindow应用篇第五章 样式表qss与自定义控件第六章 图表与曲线第七章 数据库编程第八章 项目实战:高…

FJSP:小龙虾优化算法(Crayfsh optimization algorithm,COA)求解柔性作业车间调度问题(FJSP),提供MATLAB代码

一、柔性作业车间调度问题 柔性作业车间调度问题(Flexible Job Shop Scheduling Problem,FJSP),是一种经典的组合优化问题。在FJSP问题中,有多个作业需要在多个机器上进行加工,每个作业由一系列工序组成&a…

二叉树的介绍

学习堆排序时先了解下二叉树,因为堆排序中使用了二叉树。 一、二叉树介绍 二叉树(binary tree)树的每个节点最多有2个孩子节点。注意,这里是最多有2个,也可能只有1个,或者没有孩子节点。 二叉树结构如图…

极客时间: 用 Word2Vec, LangChain, Gemma 模拟全本地检索增强生成(RAG)

每周跟踪AI热点新闻动向和震撼发展 想要探索生成式人工智能的前沿进展吗?订阅我们的简报,深入解析最新的技术突破、实际应用案例和未来的趋势。与全球数同行一同,从行业内部的深度分析和实用指南中受益。不要错过这个机会,成为AI领…

「 典型安全漏洞系列 」11.身份验证漏洞详解

身份验证是验证用户或客户端身份的过程。网站可能会暴露给任何连接到互联网的人。这使得健壮的身份验证机制成为有效的网络安全不可或缺的一部分。 1. 什么是身份验证 身份验证即认证,是验证给定用户或客户端身份的过程。身份验证漏洞使攻击者能够访问敏感数据和功…

RobotFramework测试框架(12)--第三方库

Library 关于射频指南 |机器人框架 (robotframework.org) 使用RF需要使用Library,常用的第三方库如下: 在web浏览器中进行web应用程序测试可以使用的库是 Selenium Library 在内部使用流行的 Selenium 工具的 Web 测试库Browser Library 由 Playwri…

ThingsBoard通过MQTT发送遥测数据

MQTT基础 客户端 MQTT连接 遥测上传API 案例 MQTT基础 MQTT是一种轻量级的发布-订阅消息传递协议,它可能最适合各种物联网设备。 你可以在此处找到有关MQTT的更多信息,ThingsBoard服务器支持QoS级别0(最多一次)和QoS级别1&…

【前沿模型解析】潜在扩散模 1 | LDM第一阶段-感知图像压缩总览

文章目录 0 开始~1 感知压缩的目的2 自回归编码器-解码器生成模型一览2.1 AE 自编码器2.2 VAE 变分自编码器2.3 VQ-VAE2.4 VQ-GAN 3 代码部分讲解总览 0 开始~ 从今天起呢,我们会剖析LDM(潜在扩散模型) 从去年开始,大量的生成模…

蓝桥杯嵌入式(G431)备赛笔记——按键模块设计

目录 cubeMX配置: 代码模板: 最终模板 注意: cubeMX配置: 原理图 引脚配置为上拉模式 定时器 使用定时器3(通用定时器,使用外部晶振,内部时钟),分频系数为80(从0开始则为80-1),则每1s 1m次,定时评率为为10000,对应1s 1m/10000次,频率为10ms每次 一定记得开启…

【SCI绘图】【小提琴系列1 python】绘制按分类变量分组的垂直小提琴图

SCI,CCF,EI及核心期刊绘图宝典,爆款持续更新,助力科研! 本期分享: 【SCI绘图】【小提琴系列1 python】绘制按分类变量分组的垂直小提琴图,文末附完整代码 小提琴图是一种常用的数据可视化工具…

java小作业(4)--编写一个类(第一遍)

1.题目: 2.官方代码: // 宠物基类 class Pet {protected double foodPricePerJin; // 食物单价(元/斤) protected double foodQuantityPerDay; // 每天所需食物量(斤) // 计算每天的食物花费 public…

Prefetch

Prefetch &#xff08;<link rel"prefetch">&#xff09; 是一种浏览器优化&#xff0c;它允许我们在需要后续路由或页面之前获取可能需要的资源。可以通过几种方式实现预取。它可以在 HTML 中以声明方式完成&#xff08;例如在下面的示例中&#xff09;&#…