FastApi如何快速構建一個web項目的實現(xiàn)
FastApi快速構建一個web項目

已經(jīng)使用FastApi很久了。這個一個非常優(yōu)秀的框架。和flask一樣能夠快速構建一個web服務。開發(fā)效率非常之高。今天我一個Demo來介紹一下這個框架的使用。供大家學習參考。
項目介紹
本項目主要介紹fastapi快速編寫web服務,通過案例分別介紹項目搭建,接口編寫,文檔生成,模板渲染,excel讀取,鏡像部署等項目中常見的問題。
項目目錄構成
data learning.xlsx templates index.html main.py Dockerfile README.md requirements.txt
data 目錄是存放Excel數(shù)據(jù)文件
templates 目錄是存放html模板文件
main.py 是項目的入口文件
Dockerfile 是項目通過Docker部署構建鏡像的文件
README.md 是項目的介紹文件
requirements.txt 是項目的依賴文件
項目內(nèi)容
數(shù)據(jù)文件內(nèi)容
數(shù)據(jù)文件內(nèi)容見下圖
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代碼
# 在視圖函數(shù)中傳入request對象,用于在模板對象中傳遞上下文(同時接收路徑參數(shù)info,將其傳遞到上下文中)
@app.get("/", summary="這是一個模板渲染示例")
async def index(request: Request):
# 加載excel數(shù)據(jù)
result = pd.read_excel(file_path)
# 將excel數(shù)據(jù)轉(zhuǎn)化為JSON對象
info = result.to_dict("records")
# 返回一個模板對象,同時使用上下文中的數(shù)據(jù)對模板進行渲染
return templates.TemplateResponse(
name="index.html", context={"request": request, "info": info}
)
同步接口
見代碼
@app.get("/index", summary="這是一個同步接口")
def index():
return {"key": "這是一個同步接口返回的數(shù)據(jù)"}
異步接口
見代碼
@app.get("/index/async", summary="這是一個異步接口")
def index_async():
return {"key": "這是一個異步接口返回的數(shù)據(jù)"}
項目入口文件
見代碼
main.py
import os
from pathlib import Path
import pandas as pd
import uvicorn
from fastapi import FastAPI
# 導入Request上下文對象,用來在前后臺之間傳遞參數(shù)
from starlette.requests import Request
# 導入jinja2模板引擎對象,用于后續(xù)使用
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")
# 在視圖函數(shù)中傳入request對象,用于在模板對象中傳遞上下文(同時接收路徑參數(shù)info,將其傳遞到上下文中)
@app.get("/", summary="這是一個模板渲染示例")
async def index(request: Request):
# 加載excel數(shù)據(jù)
result = pd.read_excel(file_path)
# 將excel數(shù)據(jù)轉(zhuǎn)化為JSON對象
info = result.to_dict("records")
# 返回一個模板對象,同時使用上下文中的數(shù)據(jù)對模板進行渲染
return templates.TemplateResponse(
name="index.html", context={"request": request, "info": info}
)
@app.get("/index/async", summary="這是一個異步接口")
def index_async():
return {"key": "這是一個異步接口返回的數(shù)據(jù)"}
@app.get("/index", summary="這是一個同步接口")
def index():
return {"key": "這是一個同步接口返回的數(shù)據(jù)"}
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所在的目錄,執(zhí)行下面的命令構建鏡像.
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
訪問效果
文檔效果一

文檔效果二

模板渲染效果一

到此這篇關于FastApi如何快速構建一個web項目的實現(xiàn)的文章就介紹到這了,更多相關FastApi構建web項目內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python實現(xiàn)將目錄中TXT合并成一個大TXT文件的方法
這篇文章主要介紹了Python實現(xiàn)將目錄中TXT合并成一個大TXT文件的方法,涉及Python針對目錄下文本文件的遍歷、讀取及寫入等技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07
Pyqt5實戰(zhàn)小案例之界面與邏輯分離的小計算器程序
網(wǎng)上很多PyQt5信號槽與界面分離的例子,但是真正開發(fā)起來很不方便,下面這篇文章主要給大家介紹了關于Pyqt5實戰(zhàn)小案例之界面與邏輯分離的小計算器程序,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-02-02
淺談python已知元素,獲取元素索引(numpy,pandas)
今天小編就為大家分享一篇淺談python已知元素,獲取元素索引(numpy,pandas),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
python3 循環(huán)讀取excel文件并寫入json操作
這篇文章主要介紹了python3 循環(huán)讀取excel文件并寫入json操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07

