Python Web框架:FastAPI

一:简介

FastAPI https://fastapi.org.cn/ 是一个现代、快速(高性能)的 Web 框架,用于基于标准 Python 类型提示构建 API。

教程:https://fastapi.org.cn/tutorial/

shell 复制代码
pip install fastapi

二:示例

python 复制代码
import os
import json
import logging
from typing import Any
from pydantic import BaseMode
from fastapi import FastAPI
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles


logging.basicconfig(
	level=logging.INFo,
	format="%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s"
)	

app = FastAPI(title="标题")
app.mount("/static", StaticFiles(directory="static", name="static"))

class ApiResponse(BaseModel):
	code: int
	message: str
	data: Any

# 全局异常处理器
@app.exception_handler(Exception)
def handle_exception(request: Request, exe: Exception):
	logging.error(f"异常处理,请求路径 {request.url}, 捕获到异常 {exe}")
	return JSONResponse(content={"code": 500, "message"="服务器内部错误,请联系管理员", data: None})

@app.get("/")
def root():
	logging.info("首页")
	return FileResponse("static/index.html")

@app.get("/api/user")
def get_user(request: int) -> ApiResponse:
	user = {"id": 1, "username": "melong"}
	return ApiResponse(200, "ok", user)

@app.post("/api/user")
def add_user():
	pass

@app.delete("/api/user")
def del_user(id: int):
	pass

if __name__ == "__main__":
import uvicorn
  uvicorn.run(app, host="127.0.0.1", port=8000)

三:运行

方式一

python 复制代码
pip install "fastapi[standard]"
fastapi dev "xxx.py"

方式二

python 复制代码
uvicorn xxx:app --reload

方式三(推荐)

uvicorn是Python中轻量的web服务器

python 复制代码
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
相关推荐
Liben25 分钟前
Weex开发踩坑记录
android·前端·ios
速易达网络36 分钟前
如何“训练”一个 .task 模型
python
PiaoKe___39 分钟前
云手机技术解析:从 ARM 虚拟化到 Python 自动化实战
python·智能手机·自动化
jerrywus40 分钟前
AI 写的代码能跑,为什么接手的人想跑?
前端·agent·claude
山雀~1 小时前
Web 多语言(i18n)技术方案详解
前端
学习论之费曼学习法1 小时前
无人值守AI内容矩阵实战(10):Windows 上让 Python 进程 7×24 活着
人工智能·windows·python·矩阵·powershell·进程守护
Norna1 小时前
锁文件里明明有哈希,PDM 为什么说没有?
python
大侠在此在在此1 小时前
我花了不到1块钱,用python把自己一年的1500次会话做成了个人知识库
python·llm
biu_biubiu1 小时前
我开源了 Codebook
前端·vue.js
下山1 小时前
怎么把带自研插件的 DeepSeek Harness 部署到云服务器
前端