1.FastAPI简介

1.1FastAPI是什么?

FastAPI是一个现代的,快速(高性能)python web框架。基于标准的python类型提示,使用python3.6+构建API的Web框架。

FastAPI的主要特点如下:

  • 快速:非常高的性能,与NodeJS和Go相当(这个要感谢Starlette和Pydantic),是最快的Python框架之一。

  • 快速编码:将开发速度提高约200%到300%。

  • 更少的bug:减少大约40%的开发人员人为引起的错误。

  • 直观:强大的编辑器支持,调试时间更短。

  • 简单:易于使用和学习。减少阅读文档的时间。

  • 代码简洁:尽量减少代码重复。每个参数可以声明多个功能,减少程序的bug。

  • 健壮:生产代码会自动生成交互式文档。

  • 基于标准:基于并完全兼容API的开放标准:OpenAPI和JSON模式。

1.2环境准备

  • 安装fastapi

pip install fastapi

  • 对于生产环境,还需要一个ASGI服务器,如Uvicorn或Hypercorn

pip install "uvicorn[standard]"

1.3入门示例程序

新建一个main.py,编写如下程序:

from fastapi import FastAPI
​
app = FastAPI()
​
@app.get("/")
def read_root():    
    return {"Hello": "World"}
​
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):    
    return {"item_id": item_id, "q": q}

运行程序:

uvicorn main:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [28720]
INFO:     Started server process [28722]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

命令 uvicorn main:app:

  • main:文件main.py(Python的“模块”)。

  • app:在main.py中app=FastAPI()行中创建的对象。

  • --reload:在代码更改后重新启动服务器。

在命令提示符下执行如下命令来检查程序返回结果:(我们使用curl作为请求工具)

C:\Users\Administrator>curl http://127.0.0.1:8000
{"Hello":"World"}
C:\Users\Administrator>curl http://127.0.0.1:8000/items/1
{"item_id":1,"q":null}
C:\Users\Administrator>curl http://127.0.0.1:8000/items/1?q=hello
{"item_id":1,"q":"hello"}

使用异步(async/await)实现同样的功能,定义方法时使用 async def:

from fastapi import FastAPI
​
app = FastAPI()
​
@app.get("/")
async def read_root():    
    return {"Hello": "World"}
​
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):    
    return {"item_id": item_id, "q": q}
以下为 FastAPI 的全套教程: 1. FastAPI 简介 FastAPI 是一个现代化的 Python Web 框架,它使用了 Python 3.6+ 的新特性,如类型注释、异步和协程等。它提供了高性能、易于使用和易于扩展的 API 开发体验。 FastAPI 的主要特点: - 快速:FastAPI 有着非常快的性能,可以达到甚至超过其他 Python Web 框架的速度。 - 易于使用:FastAPIAPI 代码可读性非常高,开发者可以快速理解和使用。 - 自动文档:FastAPI 自动生成 API 文档,并支持交互式 API 文档界面。 - 异步支持:FastAPI 内置支持异步和协程,可以实现非阻塞 IO 和高并发。 - 安全性:FastAPI 内置了安全性功能,包括数据验证、身份验证和授权等。 2. 安装 FastAPI 安装 FastAPI 的最简单方法是使用 pip 包管理器: ```bash pip install fastapi ``` 安装完成后,您可以使用以下命令来检查 FastAPI 的版本: ```bash pip show fastapi ``` 3. 第一个 FastAPI 应用程序 创建一个名为 "main.py" 的文件,在其中编写以下代码: ```python from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} ``` 运行该应用程序: ```bash uvicorn main:app --reload ``` 打开浏览器,输入 http://localhost:8000,您将看到以下输出: ```json {"Hello": "World"} ``` 4. 定义请求参数 FastAPI 支持多种类型的请求参数,包括路径参数、查询参数、请求体等。以下是一个示例: ```python from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q} ``` 使用以下 URL 来测试该应用程序: ``` http://localhost:8000/items/42?q=test ``` 您将看到以下输出: ```json {"item_id": 42, "q": "test"} ``` 5. 定义响应模型 FastAPI 可以自动将响应数据转换为指定的模型类。以下是一个示例: ```python from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str price: float is_offer: bool = None app = FastAPI() @app.post("/items/") async def create_item(item: Item): return item ``` 使用以下命令来测试该应用程序: ```bash curl -X POST "http://localhost:8000/items/" \ -H "accept: application/json" \ -H "Content-Type: application/json" \ -d '{"name":"test item","price":9.99}' ``` 您将看到以下输出: ```json {"name": "test item", "price": 9.99, "is_offer": null} ``` 6. 自动文档 FastAPI 可以自动生成 API 文档,并支持交互式 API 文档界面。只需在浏览器中打开以下 URL 即可: ``` http://localhost:8000/docs ``` 您将看到自动生成的文档和交互式界面。 7. 部署 FastAPI 应用程序 FastAPI 应用程序可以通过多种方式部署,包括使用服务器软件(如 Nginx、Apache)、使用容器技术(如 Docker)等。 以下是使用 Docker 部署 FastAPI 应用程序的示例: 创建一个名为 "Dockerfile" 的文件,包含以下内容: ```dockerfile FROM tiangolo/uvicorn-gunicorn-fastapi:python3.8 COPY ./app /app ``` 在同一目录下创建一个名为 "app" 的目录,将 "main.py" 文件放在其中。 构建 Docker 镜像: ```bash docker build -t fastapi-app . ``` 运行 Docker 容器: ```bash docker run -d --name fastapi-container -p 8000:80 fastapi-app ``` 现在,您可以使用以下 URL 来访问 FastAPI 应用程序: ``` http://localhost:8000 ``` 以上就是 FastAPI 的全套教程,希望对您有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Janeb1018

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值