FastApi如何快速构建一个web项目的实现
作者:Li-boss 时间:2022-06-29 07:24:10
FastApi快速构建一个web项目
已经使用FastApi很久了。这个一个非常优秀的框架。和flask一样能够快速构建一个web服务。开发效率非常之高。今天我一个Demo来介绍一下这个框架的使用。供大家学习参考。
项目介绍
本项目主要介绍fastapi快速编写web服务,通过案例分别介绍项目搭建,接口编写,文档生成,模板渲染,excel读取,镜像部署等项目中常见的问题。
项目目录构成
data
learning.xlsx
templates
index.html
main.py
Dockerfile
README.md
requirements.txt
data 目录是存放Excel数据文件
templates 目录是存放html模板文件
main.py 是项目的入口文件
Dockerfile 是项目通过Docker部署构建镜像的文件
README.md 是项目的介绍文件
requirements.txt 是项目的依赖文件
项目内容
数据文件内容
数据文件内容见下图
data/learning.xlsx
模板渲染
见代码
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>编程语言学习Demo</title>
</head>
<body>
<h1>编程语言学习</h1>
<div>
<div style="color:red; ">
<b>注意:这是一个学习的Demo</b>
</div>
</div>
<table>
<tr>
<td>语言</td>
<td>学习目标</td>
<td>学习地址</td>
</tr>
{% for my_dict in info %}
<tr>
<!-- 模板过滤器使用 -->
<td>{{my_dict.语言|replace('nan','')}}</td>
<td>{{my_dict.学习目标|replace('nan','')}}</td>
<td><a href="{{my_dict.URL|e}}" target="_blank">{{my_dict.学习地址|replace('nan','')}}</td>
</tr>
{% endfor %}
</table>
<style>
table {
/*为页面中所有的table标签添加样式*/
width: 1800px;
/*让表格居中显示*/
border: black 1px solid;
/*添加边框*/
border-spacing: 0px;
/* 去掉table
/*标签及其子标签边框之间的白色空隙*/
border-collapse: collapse;
/*去掉重合线*/
}
th {
/*为页面中所有的th标签添加样式*/
border: black 1px solid;
/*添加边框*/
}
td {
/*为页面中所有的td标签添加样式*/
border: black 1px solid;
}
</style>
</body>
</html>
python代码
# 在视图函数中传入request对象,用于在模板对象中传递上下文(同时接收路径参数info,将其传递到上下文中)
@app.get("/", summary="这是一个模板渲染示例")
async def index(request: Request):
# 加载excel数据
result = pd.read_excel(file_path)
# 将excel数据转化为JSON对象
info = result.to_dict("records")
# 返回一个模板对象,同时使用上下文中的数据对模板进行渲染
return templates.TemplateResponse(
name="index.html", context={"request": request, "info": info}
)
同步接口
见代码
@app.get("/index", summary="这是一个同步接口")
def index():
return {"key": "这是一个同步接口返回的数据"}
异步接口
见代码
@app.get("/index/async", summary="这是一个异步接口")
def index_async():
return {"key": "这是一个异步接口返回的数据"}
项目入口文件
见代码
main.py
import os
from pathlib import Path
import pandas as pd
import uvicorn
from fastapi import FastAPI
# 导入Request上下文对象,用来在前后台之间传递参数
from starlette.requests import Request
# 导入jinja2模板引擎对象,用于后续使用
from starlette.templating import Jinja2Templates
app = FastAPI()
# 实例化一个模板引擎对象,指定模板所在路径
templates = Jinja2Templates(directory="templates")
data_path = os.path.abspath(Path("data"))
# 获取文件路径
file_path = os.path.join(data_path, "learning.xlsx")
# 在视图函数中传入request对象,用于在模板对象中传递上下文(同时接收路径参数info,将其传递到上下文中)
@app.get("/", summary="这是一个模板渲染示例")
async def index(request: Request):
# 加载excel数据
result = pd.read_excel(file_path)
# 将excel数据转化为JSON对象
info = result.to_dict("records")
# 返回一个模板对象,同时使用上下文中的数据对模板进行渲染
return templates.TemplateResponse(
name="index.html", context={"request": request, "info": info}
)
@app.get("/index/async", summary="这是一个异步接口")
def index_async():
return {"key": "这是一个异步接口返回的数据"}
@app.get("/index", summary="这是一个同步接口")
def index():
return {"key": "这是一个同步接口返回的数据"}
if __name__ == "__main__":
# 启动程序
uvicorn.run(app="main:app", host="0.0.0.0", port=8000, reload=True)
项目依赖
requirements.txt
fastapi==0.94.1
uvicorn==0.21.0
jinja2==3.1.2
pandas==1.5.3
openpyxl==3.1.2
gunicorn==20.1.0
项目部署
项目构建文件
Dockerfile
FROM python:3.8.16-slim-buster
LABEL MAINTAINER Li-boss "CSDN Li-boss"
COPY ./ /var/demo
RUN pip install -r /var/demo/requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
WORKDIR /var/demo
EXPOSE 8000
CMD gunicorn main:app -b 0.0.0.0:8000 --forwarded-allow-ips='*' -w 4 -k uvicorn.workers.UvicornWorker
进入到Dockerfile所在的目录,执行下面的命令构建镜像.
docker build test_demo:v1 .
启动容器
docker run -it -p 8000:8000 test_demo:v1
访问地址
http://localhost:8000/
# 文档地址:
http://localhost:8000/docs
http://localhost:8000/redoc
访问效果
文档效果一
文档效果二
模板渲染效果一
来源:https://blog.csdn.net/qq_33196814/article/details/129718998
标签:FastApi,构建,web
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Django框架下在URLconf中指定视图缓存的方法
2023-10-03 01:54:28
CentOS 6.5中安装Python 3.6.2的方法步骤
2022-10-11 09:13:43
python调用fortran模块
2023-12-22 23:36:40
一个不错的javascript加密解密算法源码
2010-03-28 13:12:00
Python第三方库xlrd/xlwt的安装与读写Excel表格
2023-12-16 22:52:34
python实现CTC以及案例讲解
2023-04-18 22:04:13
![](https://img.aspxhome.com/file/2023/6/92176_0s.png)
Python字符串中查找子串小技巧
2022-04-16 10:58:04
Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的问题
2022-06-09 20:07:37
![](https://img.aspxhome.com/file/2023/9/109659_0s.jpg)
js如何读取csv内容拼接成json
2023-08-13 02:20:14
![](https://img.aspxhome.com/file/2023/4/56034_0s.png)
python的concat等多种用法详解
2022-08-14 23:37:18
Flask request 对象介绍
2022-11-01 23:45:35
![](https://img.aspxhome.com/file/2023/3/78543_0s.png)
教你如何在SQL Server计算机列和平均值
2009-01-20 15:10:00
python将字母转化为数字实例方法
2021-12-04 03:40:17
![](https://img.aspxhome.com/file/2023/0/109890_0s.png)
一文带你掌握Pyecharts地理数据可视化的方法
2023-01-10 03:52:50
![](https://img.aspxhome.com/file/2023/5/109505_0s.png)
Python中__init__和__new__的区别详解
2023-09-24 13:14:17
教你使用Python的pygame模块实现拼图游戏
2022-06-28 03:20:20
Python实现改变与矩形橡胶的线条的颜色代码示例
2022-08-02 08:16:26
![](https://img.aspxhome.com/file/2023/4/80454_0s.png)
彻底弄懂CSS盒子模式之一(DIV布局快速入门)
2007-05-11 17:03:00
![](https://img.aspxhome.com/file/uploadpic/20075/200751117352545.gif)
Python基础教程之tcp socket编程详解及简单实例
2021-04-18 12:04:29
Python设置默认编码为utf8的方法
2023-09-23 16:08:34