Python實(shí)現(xiàn)Web服務(wù)器FastAPI的步驟詳解
1、簡介

FastAPI 是一個用于構(gòu)建 API 的現(xiàn)代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于標(biāo)準(zhǔn)的 Python類型提示。
文檔: https://fastapi.tiangolo.com
源碼: https://github.com/tiangolo/fastapi
關(guān)鍵特性:
- 快速:可與 NodeJS 和 Go 比肩的極高性能(歸功于 Starlette 和 Pydantic)。最快的 Python web 框架之一。
- 高效編碼:提高功能開發(fā)速度約 200% 至 300%。*
- 更少 bug:減少約 40% 的人為(開發(fā)者)導(dǎo)致錯誤。*
- 智能:極佳的編輯器支持。處處皆可自動補(bǔ)全,減少調(diào)試時間。
- 簡單:設(shè)計的易于使用和學(xué)習(xí),閱讀文檔的時間更短。
- 簡短:使代碼重復(fù)最小化。通過不同的參數(shù)聲明實(shí)現(xiàn)豐富功能。bug 更少。
- 健壯:生產(chǎn)可用級別的代碼。還有自動生成的交互式文檔。
- 標(biāo)準(zhǔn)化:基于(并完全兼容)API 的相關(guān)開放標(biāo)準(zhǔn):OpenAPI (以前被稱為 Swagger) 和 JSON Schema。
2、安裝
pip install fastapi or pip install fastapi[all]

運(yùn)行服務(wù)器的命令如下:
uvicorn main:app --reload
3、官方示例
使用 FastAPI 需要 Python 版本大于等于 3.6。
3.1 入門示例 Python測試代碼如下(main.py):
# -*- coding:utf-8 -*-
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}運(yùn)行結(jié)果如下:
運(yùn)行服務(wù)器的命令如下:
uvicorn main:app --reload



3.2 跨域CORS
CORS 或者「跨域資源共享」 指瀏覽器中運(yùn)行的前端擁有與后端通信的 JavaScript 代碼,而后端處于與前端不同的「源」的情況。
源是協(xié)議(http,https)、域(myapp.com,localhost,localhost.tiangolo.com)以及端口(80、443、8080)的組合。因此,這些都是不同的源:
http://localhost https://localhost http://localhost:8080
Python測試代碼如下(test_fastapi.py):
# -*- coding:utf-8 -*-
from typing import Union
from fastapi import FastAPI, Request
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# 讓app可以跨域
# origins = ["*"]
origins = [
"http://localhost.tiangolo.com",
"https://localhost.tiangolo.com",
"http://localhost",
"http://localhost:8080",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# @app.get("/")
# async def root():
# return {"Hello": "World"}
@app.get("/")
def read_root():
return {"message": "Hello World,愛看書的小沐"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
@app.get("/api/sum")
def get_sum(req: Request):
a, b = req.query_params['a'], req.query_params['b']
return int(a) + int(b)
@app.post("/api/sum2")
async def get_sum(req: Request):
content = await req.json()
a, b = content['a'], content['b']
return a + b
@app.get("/api/sum3")
def get_sum2(a: int, b: int):
return int(a) + int(b)
if __name__ == "__main__":
uvicorn.run("test_fastapi:app", host="127.0.0.1", port=8000
, log_level="info", reload=True, debug=True)運(yùn)行結(jié)果如下:



FastAPI 會自動提供一個類似于 Swagger 的交互式文檔,我們輸入 “localhost:8000/docs” 即可進(jìn)入。

3.3 文件操作
返回 json 數(shù)據(jù)可以是:JSONResponse、UJSONResponse、ORJSONResponse,Content-Type 是 application/json;返回 html 是 HTMLResponse,Content-Type 是 text/html;返回 PlainTextResponse,Content-Type 是 text/plain。
還有三種響應(yīng),分別是返回重定向、字節(jié)流、文件。
(1)Python測試重定向代碼如下:
# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
import uvicorn
app = FastAPI()
@app.get("/index")
async def index():
return RedirectResponse("https://www.baidu.com")
@app.get("/")
def main():
return {"message": "Hello World,愛看書的小沐"}
if __name__ == "__main__":
uvicorn.run("test_fastapi:app", host="127.0.0.1", port=8000
, log_level="info", reload=True, debug=True)運(yùn)行結(jié)果如下:

(2)Python測試字節(jié)流代碼如下:
# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
import uvicorn
app = FastAPI()
async def test_bytearray():
for i in range(5):
yield f"byteArray: {i} bytes ".encode("utf-8")
@app.get("/index")
async def index():
return StreamingResponse(test_bytearray())
@app.get("/")
def main():
return {"message": "Hello World,愛看書的小沐"}
if __name__ == "__main__":
uvicorn.run("test_fastapi:app", host="127.0.0.1", port=8000
, log_level="info", reload=True, debug=True)運(yùn)行結(jié)果如下:

(3)Python測試文本文件代碼如下:
# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
import uvicorn
app = FastAPI()
@app.get("/index")
async def index():
return StreamingResponse(open("test_tornado.py", encoding="utf-8"))
@app.get("/")
def main():
return {"message": "Hello World,愛看書的小沐"}
if __name__ == "__main__":
uvicorn.run("test_fastapi:app", host="127.0.0.1", port=8000
, log_level="info", reload=True, debug=True)運(yùn)行結(jié)果如下:

(4)Python測試二進(jìn)制文件代碼如下:
# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse, StreamingResponse
import uvicorn
app = FastAPI()
@app.get("/download_file")
async def index():
return FileResponse("test_fastapi.py", filename="save.py")
@app.get("/get_file/")
async def download_files():
return FileResponse("test_fastapi.py")
@app.get("/get_image/")
async def download_files_stream():
f = open("static\\images\\sheep0.jpg", mode="rb")
return StreamingResponse(f, media_type="image/jpg")
@app.get("/")
def main():
return {"message": "Hello World,愛看書的小沐"}
if __name__ == "__main__":
uvicorn.run("test_fastapi:app", host="127.0.0.1", port=8000
, log_level="info", reload=True, debug=True)運(yùn)行結(jié)果如下:



3.4 WebSocket Python測試代碼如下:
# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from fastapi.websockets import WebSocket
import uvicorn
app = FastAPI()
@app.websocket("/myws")
async def ws(websocket: WebSocket):
await websocket.accept()
while True:
# data = await websocket.receive_bytes()
# data = await websocket.receive_json()
data = await websocket.receive_text()
print("received: ", data)
await websocket.send_text(f"received: {data}")
@app.get("/")
def main():
return {"message": "Hello World,愛看書的小沐"}
if __name__ == "__main__":
uvicorn.run("test_fastapi:app", host="127.0.0.1", port=8000
, log_level="info", reload=True, debug=True)HTML客戶端測試代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tornado Websocket Test</title>
</head>
<body>
<body onload='onLoad();'>
Message to send: <input type="text" id="msg"/>
<input type="button" onclick="sendMsg();" value="發(fā)送"/>
</body>
</body>
<script type="text/javascript">
var ws;
function onLoad() {
ws = new WebSocket("ws://127.0.0.1:8000/myws");
ws.onopen = function() {
console.log('connect ok.')
ws.send("Hello, world");
};
ws.onmessage = function (evt) {
console.log(evt.data)
};
ws.onclose = function () {
console.log("onclose")
}
}
function sendMsg() {
ws.send(document.getElementById('msg').value);
}
</script>
</html>運(yùn)行結(jié)果如下:


到此這篇關(guān)于Python實(shí)現(xiàn)Web服務(wù)器(FastAPI的文章就介紹到這了,更多相關(guān)Python Web服務(wù)器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
實(shí)操Python爬取覓知網(wǎng)素材圖片示例
大家好,本篇文章介紹的是實(shí)操Python爬取覓知網(wǎng)素材圖片示例,感興趣的朋友趕快來看一看吧,對你有用的話記得收藏起來,方便下次瀏覽2021-11-11
python使用cartopy庫繪制臺風(fēng)路徑代碼
大家好,本篇文章主要講的是python使用cartopy庫繪制臺風(fēng)路徑代碼,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-02-02
國產(chǎn)麒麟系統(tǒng)kylin部署python項目詳細(xì)步驟
這篇文章主要給大家介紹了關(guān)于國產(chǎn)麒麟系統(tǒng)kylin部署python項目的相關(guān)資料,文中通過代碼示例介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09
Anaconda配置各版本Pytorch的實(shí)現(xiàn)
本文是整理目前全版本pytorch深度學(xué)習(xí)環(huán)境配置指令,以下指令適用Windows操作系統(tǒng),在Anaconda Prompt中運(yùn)行,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08
python numpy生成等差數(shù)列、等比數(shù)列的實(shí)例
今天小編就為大家分享一篇python numpy生成等差數(shù)列、等比數(shù)列的實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
Python?操作Excel-openpyxl模塊用法實(shí)例
openpyxl 模塊是一個讀寫 Excel 2010 文檔的 Python 庫,如果要處理更早格式的 Excel 文 檔,需要用到額外的庫,openpyxl 是一個比較綜合的工具,能夠同時讀取和修改 Excel 文檔,這篇文章主要介紹了Python?操作Excel-openpyxl模塊使用,需要的朋友可以參考下2023-05-05

