Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

第 4 章 FastAPI

目录

4.1. HTML - FastAPI 加载 index.html
4.2. 路径参数
4.3. GET 请求
4.3.1. 返回图片
4.4. Post 请求
4.4.1. From 数据
4.4.2. Json 数据转为 dict
4.4.3. Data 原始数据
4.4.4. POST 接收 JSON 数据
4.4.5. 上传文件
4.5. 响应返回
4.5.1. Response
4.5.2. 返回 HTMl
4.5.3. PlainTextResponse
4.5.4. RedirectResponse
4.5.5. StreamingResponse
4.5.6. FileResponse
4.6. api_route
4.7. slowapi 流向控制
4.8. 异步执行
4.9. 缓存
4.9.1. 缓存 Json 数据结构
4.9.2. 自定义 key
4.10. HTTP Auth
4.11. SSE
4.12. 解决 Sqlalchemy 返回模型无法打印的问题
4.13. 返回二维码图片
4.14. Fief 认证框架

4.1. HTML - FastAPI 加载 index.html

首先需要创建一个新的Python虚拟环境,然后通过pip安装FastAPI和uvicorn。

		
$ mkdir netkiller
$ cd netkiller
$ python3 -m venv venv
$ source venv/bin/activate
$ pip install fastapi uvicorn		
		
		

在项目目录下创建一个名为 index.html 的HTML文件,内容如下:

		
<!DOCTYPE html>
<html>
<head>
    <title>FastAPI example by netkiller</title>
</head>
<body>
    <h1>Hello, FastAPI!</h1>
    <p>This is an example of loading an HTML file using FastAPI.</p>
</body>
</html>
		
		

创建一个名为 main.py 的Python文件,代码如下:

		
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

app.mount("/", StaticFiles(directory=".", html=True))

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

启动服务

		
$ uvicorn main:app --reload