Login
网站首页 > 文章中心 > 其它

Python微服务开发之使用FastAPI构建高效API

作者:小编 更新时间:2023-08-16 16:28:15 浏览量:233人看过

我来详细讲解一下.

Python微服务开发之使用FastAPI构建高效API

本文将介绍如何使用FastAPI构建高效API,内容包括:

FastAPI简介

FastAPI开发环境的搭建

FastAPI基本使用和注意事项

使用FastAPI构建示例API

FastAPI简介

FastAPI的优点:

快速:FastAPI是目前最快的Python web框架之一,性能与Node.js和Go相当.

易于使用:FastAPI的API设计简单明了,易于快速上手.

与OpenAPI的兼容性:FastAPI允许自动生成API文档,且与自动生成的OpenAPI文档兼容.

基于标准:FastAPI是基于标准Python类型注释进行构建的,这使得该框架易于学习和调试.

FastAPI开发环境的搭建

搭建FastAPI开发环境的主要步骤如下:

安装FastAPI和uvicorn

bash $ pip install fastapi uvicorn[standard]

"uvicorn[standard]"是一个ASGI Web Server,能够非常快速地服务FastAPI应用程序.

以上三个步骤完成后,我们就可以开始使用FastAPI构建API了.

FastAPI基本使用和注意事项

在使用FastAPI构建API之前,需要了解以下基本概念和注意事项:

路由(Route)

在FastAPI中,一个路由是一个可以映射到某个URL的函数.使用装饰器@router.XXX(XXX为HTTP请求方法,如@router.get)将一个函数转为一个路由.


@app.route("/")
async def index():
return {"Hello": "World"}


请求类型定义(Type Hints)

定义参数类型可以确保类型的正确性


@app.route("/{name}")
async def hello_name(name: str):
return {"Hello": name}


响应(Response)

FastAPI支持多种格式的响应,如JSON、HTML等.可以使用Pydantic将响应格式化:


from fastapi.responses import JSONResponse
from pydantic import BaseModel

class User(BaseModel):
name: str
age: int

@app.route("/")
async def index():
user = User(name="Alice", age=20)
return JSONResponse(content=user.dict())


异步(Async)

FastAPI支持异步编程,可以非常高效地处理并发请求.


@app.route("/{name}")
async def hello_name(name: str):
await asyncio.sleep(1)
return {"Hello": name}


中间件(Middleware)

FastAPI支持中间件,可以在处理请求和响应之间执行一系列操作.可以使用FastAPI的app.add_middleware()方法添加中间件.


from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware

app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=["example.com"],
)


使用FastAPI构建示例API

下面是两个示例API,一个是查询天气信息API,一个是生成二维码API.

查询天气信息API

下面的代码是一个简单的查询天气信息API,使用了aiohttp库发送HTTP请求获取天气信息并返回:


import aiohttp
from fastapi import FastAPI
from fastapi import Depends

app = FastAPI()

async def get_weather(city: str) -> str:
async with aiohttp.ClientSession() as session:
    async with session.get(f'http://wthrcdn.etouch.cn/weather_mini?city={city}') as resp:
        resp.raise_for_status()
        content = await resp.json(content_type=None)
        if content and content['status'] == 1000:
            data = content.get('data', {})
            return f"{data['city']}天气:{data['forecast'][0]['type']}, 当前温度{data['wendu']}℃."
        else:
            raise ValueError(f"Failed to get weather for '{city}': {content}")

@app.get("/weather/{city}")
async def weather(city: str, weather: str = Depends(get_weather)):
return {"city": city, "weather": weather}


生成二维码API

下面的代码是一个简单的生成二维码API,使用了qrcode库生成二维码:


import io
import qrcode
from fastapi import FastAPI

app = FastAPI()

@app.get("/qrcode")
async def generate_qr_code(data: str):
img = qrcode.make(data)
in_mem_file = io.BytesIO()
img.save(in_mem_file, format="PNG")
in_mem_file.seek(0)
return in_mem_file.getvalue()


好了,全部的使用FastAPI构建高效API的完整攻略,希望对你有所帮助.

版权声明:倡导尊重与保护知识产权。未经许可,任何人不得复制、转载、或以其他方式使用本站《原创》内容,违者将追究其法律责任。本站文章内容,部分图片来源于网络,如有侵权,请联系我们修改或者删除处理。

编辑推荐

热门文章