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)
相关推荐
AlienZHOU4 小时前
DeepSeek Harness 插件:HTML 实时可视化编辑
前端·agent·deepseek
CTA量化套保5 小时前
近期零基础量化学习:先分阶段,再用 AI 检查缺口
人工智能·python
剪刀石头布啊6 小时前
javascript手动实现继承
前端
清水白石0086 小时前
Python 死锁排查全攻略:从线程卡死到锁依赖定位与工程化修复
linux·网络·python
Elias不吃糖6 小时前
Langfuse 入门:Trace、Prompt、Dataset、Experiment、Evaluator
前端·python·prompt·langfuse
vipbic7 小时前
一个前端的 9 天重构:我是怎么用 Codex 重做航栈的
前端·javascript·后端
TechWayfarer7 小时前
批量查IP归属地,在线API、脚本、离线库怎么选?三种方案实测对比
网络·python·网络协议·tcp/ip
七牛开发者8 小时前
为什么 Go 很适合 AI 辅助开发?
数据库·人工智能·python·elasticsearch·log4j
河南凹凸环境艺术设计8 小时前
性价比高的民宿酒店设计企业
大数据·人工智能·python