Python Web开发新选择:FastAPI框架详细教程

Python Web开发新选择:FastAPI框架详细教程

简介

FastAPI是一个用于构建API的现代、快速(高性能)的Web框架,它基于Python 3.6+的类型提示。本文将通过具体的示例,详细介绍如何使用FastAPI进行Web开发。

一、FastAPI简介

1. FastAPI能做什么?

FastAPI适用于构建:

  • Web站点
  • Web API
  • 测试平台
  • 持续集成工具
  • 自动生成API文档
  • 2. 为什么要学习FastAPI?

    FastAPI的优势包括:

  • 性能强:与NodeJS和Go相媲美
  • 简化数据验证:基于Python类型提示
  • 自动生成文档:支持Swagger UI和ReDoc
  • 支持异步编程:原生支持异步请求处理
  • 依赖注入系统:强大的依赖管理和注入系统
  • 二、环境准备

    1. 编译器工具

    推荐使用Python和PyCharm作为开发工具。

    2. Python安装

    参考Python安装教程。

    3. PyCharm安装

    参考PyCharm安装教程。

    4. 安装虚拟环境

  • 创建项目工程:mkdir myproject && cd myproject
  • 安装虚拟环境:python -m venv venv
  • 激活虚拟环境:
  • Windows: .\venv\Scripts\activate
  • macOS/Linux: source venv/bin/activate
  • 安装FastAPI:pip install fastapi[all]
  • 三、FastAPI基础教程

    1. 开启服务和接口访问

    创建main.py文件,并添加以下代码:

    from fastapi import FastAPI
    import uvicorn
    
    app = FastAPI()
    
    @app.get("/")
    def index():
        return {"message": "Hello World"}
    
    if __name__ == "__main__":
        uvicorn.run(app, host="0.0.0.0", port=8000)
    

    运行uvicorn main:app --reload启动开发服务器,并访问http://127.0.0.1:8000查看结果。

    2. 处理JSON数据

    from fastapi import FastAPI, JSONResponse
    from pydantic import BaseModel
    
    app = FastAPI()
    
    class Item(BaseModel):
        name: str
        description: str = None
        price: float
        tax: float = None
    
    @app.post("/items/")
    async def create_item(item: Item):
        return JSONResponse(content={"item": item.dict()}, status_code=201)
    

    3. API文档在线生成

    FastAPI自动为每个接口生成文档,访问http://127.0.0.1:8000/docs查看Swagger UI。

    4. 获取URL参数

    from fastapi import FastAPI, Path
    
    app = FastAPI()
    
    @app.get("/users/{user_id}")
    async def read_user(user_id: int = Path(..., title="The user identifier")):
        return {"user_id": user_id}
    

    5. 获取请求头参数

    from fastapi import FastAPI, Header
    
    app = FastAPI()
    
    @app.get("/items/")
    async def read_item(token: str = Header(None)):
        return {"token": token}
    

    6. 表单数据获取

    安装python-multipartpip install python-multipart

    from fastapi import FastAPI, Form
    
    app = FastAPI()
    
    @app.post("/login/")
    async def login(username: str = Form(...), password: str = Form(...)):
        return {"username": username}
    

    7. 自定义返回JSON信息

    from fastapi import FastAPI
    from fastapi.responses import JSONResponse
    
    app = FastAPI()
    
    @app.get("/users/me")
    async def read_users_me():
        return JSONResponse(content={"username": "john doe"}, status_code=200)
    

    8. 自定义返回HTML

    from fastapi import FastAPI
    from fastapi.responses import HTMLResponse
    
    app = FastAPI()
    
    @app.get("/hello")
    async def say_hello():
        return HTMLResponse("<html><body><h1>Hello, World!</h1></body></html>")
    

    9. 自定义返回文件

    from fastapi import FastAPI
    from starlette.responses import FileResponse
    
    app = FastAPI()
    
    @app.get("/files/{filename}")
    async def send_file(filename: str):
        return FileResponse(f"./static/{filename}", media_type="image/png")
    

    10. 自定义返回HTML页面

    from fastapi import FastAPI, Request
    from fastapi.templating import Jinja2Templates
    
    app = FastAPI()
    templates = Jinja2Templates(directory="templates")
    
    @app.get("/")
    async def main(request: Request):
        return templates.TemplateResponse("index.html", {"request": request})
    

    11. 代办事项小案例

    创建Todo模型和简单的CRUD操作。

    12. 绑定数据库

    使用Tortoise-ORM或SQLAlchemy进行数据库操作。

    13. 数据库访问

    定义模型和数据库会话,执行查询。

    14. 数据库写入

    插入和更新数据库记录。

    结语

    FastAPI以其现代化的设计和强大的功能,成为了Python Web开发的新选择。本文提供了详细的示例,帮助你快速上手FastAPI,并在你的项目中发挥其强大的能力。希望这能帮助你快速上手FastAPI,并在你的项目中有效地使用它。

    作者:车载testing

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python Web开发新选择:FastAPI框架详细教程

    发表回复