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)
相关推荐
BD_Marathon2 小时前
安装Jupyter notebook
ide·python·jupyter
Zlzxzw2 小时前
End-to-End Autonomous Generation of Human Assembly Plans
python
Wellijohn3 小时前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍
后端·python·性能优化
feixing_fx4 小时前
解构与展开:可读性和性能的取舍
开发语言·前端·javascript·前端框架
Logintern095 小时前
deep agents 多智能体模式——规划与委派
python·langchain
前端架构师-老李5 小时前
html教程:header、nav、main、footer 四个标签各管哪一块?
前端·html
烟雨空灵6 小时前
25 天做了个独立开发者作品橱窗,收录 340+ 件作品,代码全开源
前端·node.js
wangruofeng6 小时前
怎么让你的项目更好看?用 UI Lab 练设计原则,给界面去 AI 味
前端·aigc·ai编程
2601_967980116 小时前
Python 办公自动化合集 ⑰:Excel自动计算——总和/平均分/最大值
python·pycharm·办公自动化·数据处理·excel自动计算
用户69371750013847 小时前
AI 越强,为什么我们反而越来越担心失业?
前端·后端·github