FastApi如何快速構(gòu)建一個(gè)web項(xiàng)目的實(shí)現(xiàn)
FastApi快速構(gòu)建一個(gè)web項(xiàng)目

已經(jīng)使用FastApi很久了。這個(gè)一個(gè)非常優(yōu)秀的框架。和flask一樣能夠快速構(gòu)建一個(gè)web服務(wù)。開(kāi)發(fā)效率非常之高。今天我一個(gè)Demo來(lái)介紹一下這個(gè)框架的使用。供大家學(xué)習(xí)參考。
項(xiàng)目介紹
本項(xiàng)目主要介紹fastapi快速編寫(xiě)web服務(wù),通過(guò)案例分別介紹項(xiàng)目搭建,接口編寫(xiě),文檔生成,模板渲染,excel讀取,鏡像部署等項(xiàng)目中常見(jiàn)的問(wèn)題。
項(xiàng)目目錄構(gòu)成
data learning.xlsx templates index.html main.py Dockerfile README.md requirements.txt
data 目錄是存放Excel數(shù)據(jù)文件
templates 目錄是存放html模板文件
main.py 是項(xiàng)目的入口文件
Dockerfile 是項(xiàng)目通過(guò)Docker部署構(gòu)建鏡像的文件
README.md 是項(xiàng)目的介紹文件
requirements.txt 是項(xiàng)目的依賴(lài)文件
項(xiàng)目?jī)?nèi)容
數(shù)據(jù)文件內(nèi)容
數(shù)據(jù)文件內(nèi)容見(jiàn)下圖
data/learning.xlsx

模板渲染
見(jiàn)代碼
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>編程語(yǔ)言學(xué)習(xí)Demo</title>
</head>
<body>
<h1>編程語(yǔ)言學(xué)習(xí)</h1>
<div>
<div style="color:red; ">
<b>注意:這是一個(gè)學(xué)習(xí)的Demo</b>
</div>
</div>
<table>
<tr>
<td>語(yǔ)言</td>
<td>學(xué)習(xí)目標(biāo)</td>
<td>學(xué)習(xí)地址</td>
</tr>
{% for my_dict in info %}
<tr>
<!-- 模板過(guò)濾器使用 -->
<td>{{my_dict.語(yǔ)言|replace('nan','')}}</td>
<td>{{my_dict.學(xué)習(xí)目標(biāo)|replace('nan','')}}</td>
<td><a href="{{my_dict.URL|e}}" target="_blank">{{my_dict.學(xué)習(xí)地址|replace('nan','')}}</td>
</tr>
{% endfor %}
</table>
<style>
table {
/*為頁(yè)面中所有的table標(biāo)簽添加樣式*/
width: 1800px;
/*讓表格居中顯示*/
border: black 1px solid;
/*添加邊框*/
border-spacing: 0px;
/* 去掉table
/*標(biāo)簽及其子標(biāo)簽邊框之間的白色空隙*/
border-collapse: collapse;
/*去掉重合線(xiàn)*/
}
th {
/*為頁(yè)面中所有的th標(biāo)簽添加樣式*/
border: black 1px solid;
/*添加邊框*/
}
td {
/*為頁(yè)面中所有的td標(biāo)簽添加樣式*/
border: black 1px solid;
}
</style>
</body>
</html>
python代碼
# 在視圖函數(shù)中傳入request對(duì)象,用于在模板對(duì)象中傳遞上下文(同時(shí)接收路徑參數(shù)info,將其傳遞到上下文中)
@app.get("/", summary="這是一個(gè)模板渲染示例")
async def index(request: Request):
# 加載excel數(shù)據(jù)
result = pd.read_excel(file_path)
# 將excel數(shù)據(jù)轉(zhuǎn)化為JSON對(duì)象
info = result.to_dict("records")
# 返回一個(gè)模板對(duì)象,同時(shí)使用上下文中的數(shù)據(jù)對(duì)模板進(jìn)行渲染
return templates.TemplateResponse(
name="index.html", context={"request": request, "info": info}
)
同步接口
見(jiàn)代碼
@app.get("/index", summary="這是一個(gè)同步接口")
def index():
return {"key": "這是一個(gè)同步接口返回的數(shù)據(jù)"}
異步接口
見(jiàn)代碼
@app.get("/index/async", summary="這是一個(gè)異步接口")
def index_async():
return {"key": "這是一個(gè)異步接口返回的數(shù)據(jù)"}
項(xiàng)目入口文件
見(jiàn)代碼
main.py
import os
from pathlib import Path
import pandas as pd
import uvicorn
from fastapi import FastAPI
# 導(dǎo)入Request上下文對(duì)象,用來(lái)在前后臺(tái)之間傳遞參數(shù)
from starlette.requests import Request
# 導(dǎo)入jinja2模板引擎對(duì)象,用于后續(xù)使用
from starlette.templating import Jinja2Templates
app = FastAPI()
# 實(shí)例化一個(gè)模板引擎對(duì)象,指定模板所在路徑
templates = Jinja2Templates(directory="templates")
data_path = os.path.abspath(Path("data"))
# 獲取文件路徑
file_path = os.path.join(data_path, "learning.xlsx")
# 在視圖函數(shù)中傳入request對(duì)象,用于在模板對(duì)象中傳遞上下文(同時(shí)接收路徑參數(shù)info,將其傳遞到上下文中)
@app.get("/", summary="這是一個(gè)模板渲染示例")
async def index(request: Request):
# 加載excel數(shù)據(jù)
result = pd.read_excel(file_path)
# 將excel數(shù)據(jù)轉(zhuǎn)化為JSON對(duì)象
info = result.to_dict("records")
# 返回一個(gè)模板對(duì)象,同時(shí)使用上下文中的數(shù)據(jù)對(duì)模板進(jìn)行渲染
return templates.TemplateResponse(
name="index.html", context={"request": request, "info": info}
)
@app.get("/index/async", summary="這是一個(gè)異步接口")
def index_async():
return {"key": "這是一個(gè)異步接口返回的數(shù)據(jù)"}
@app.get("/index", summary="這是一個(gè)同步接口")
def index():
return {"key": "這是一個(gè)同步接口返回的數(shù)據(jù)"}
if __name__ == "__main__":
# 啟動(dòng)程序
uvicorn.run(app="main:app", host="0.0.0.0", port=8000, reload=True)
項(xiàng)目依賴(lài)
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
項(xiàng)目部署
項(xiàng)目構(gòu)建文件
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
進(jìn)入到Dockerfile所在的目錄,執(zhí)行下面的命令構(gòu)建鏡像.
docker build test_demo:v1 .
啟動(dòng)容器
docker run -it -p 8000:8000 test_demo:v1
訪(fǎng)問(wèn)地址
http://localhost:8000/
# 文檔地址:
http://localhost:8000/docs
http://localhost:8000/redoc
訪(fǎng)問(wèn)效果
文檔效果一

文檔效果二

模板渲染效果一

到此這篇關(guān)于FastApi如何快速構(gòu)建一個(gè)web項(xiàng)目的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)FastApi構(gòu)建web項(xiàng)目?jī)?nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pytorch模型轉(zhuǎn)換為onnx可視化(使用netron)
netron 是一個(gè)非常好用的網(wǎng)絡(luò)結(jié)構(gòu)可視化工具,但是netron對(duì)pytorch模型的支持還不成熟,這篇文章主要介紹了pytorch模型轉(zhuǎn)換為onnx,并使用netron可視化,需要的朋友可以參考下2023-05-05
matplotlib如何設(shè)置坐標(biāo)軸刻度的個(gè)數(shù)及標(biāo)簽的方法總結(jié)
這里介紹兩種設(shè)置坐標(biāo)軸刻度的方法,一種是利用pyplot提交的api去進(jìn)行設(shè)置,另一種是通過(guò)調(diào)用面向?qū)ο蟮腶pi, 即通過(guò)matplotlib.axes.Axes去設(shè)置,需要的朋友可以參考下2021-06-06
關(guān)于sklearn包導(dǎo)入錯(cuò)誤:ImportError:?cannot?import?name Type解
這篇文章主要介紹了關(guān)于sklearn包導(dǎo)入錯(cuò)誤:ImportError:?cannot?import?name‘Type‘解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
pytorch教程實(shí)現(xiàn)mnist手寫(xiě)數(shù)字識(shí)別代碼示例
這篇文章主要講解了pytorch教程中如何實(shí)現(xiàn)mnist手寫(xiě)數(shù)字識(shí)別,文中附有詳細(xì)的代碼示例,test準(zhǔn)確率98%,有需要的朋友可以借鑒參考下2021-09-09
python使用兩種發(fā)郵件的方式smtp和outlook示例
本篇文章主要介紹了python使用兩種發(fā)郵件的方式smtp和outlook示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-06-06
python?chinesecalendar報(bào)錯(cuò):"no?available?data?for?ye
這篇文章主要介紹了python?chinesecalendar報(bào)錯(cuò):“no?available?data?for?year?{},?only?year?between?[{},?{}]?supported“的相關(guān)知識(shí),需要的朋友可以參考下2023-03-03
python實(shí)現(xiàn)車(chē)輛跟隨滑模控制的實(shí)例
這篇文章主要介紹了python實(shí)現(xiàn)車(chē)輛跟隨滑??刂?采用指數(shù)趨近律、等速趨近律、準(zhǔn)滑??刂频姆椒ㄍ瓿绍?chē)輛跟隨問(wèn)題的仿真,運(yùn)行結(jié)果以圖片形式保存在同目錄下,需要的朋友可以參考下2022-05-05
使用tensorflow實(shí)現(xiàn)矩陣分解方式
今天小編就為大家分享一篇使用tensorflow實(shí)現(xiàn)矩陣分解方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02
PyTorch 解決Dataset和Dataloader遇到的問(wèn)題
今天小編就為大家分享一篇PyTorch 解決Dataset和Dataloader遇到的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-01-01

