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

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

運行服務器的命令如下:
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"}運行結果如下:
運行服務器的命令如下:
uvicorn main:app --reload



3.2 跨域CORS
CORS 或者「跨域資源共享」 指瀏覽器中運行的前端擁有與后端通信的 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)運行結果如下:



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

3.3 文件操作
返回 json 數(shù)據(jù)可以是:JSONResponse、UJSONResponse、ORJSONResponse,Content-Type 是 application/json;返回 html 是 HTMLResponse,Content-Type 是 text/html;返回 PlainTextResponse,Content-Type 是 text/plain。
還有三種響應,分別是返回重定向、字節(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)運行結果如下:

(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)運行結果如下:

(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)運行結果如下:

(4)Python測試二進制文件代碼如下:
# -*- 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)運行結果如下:



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>運行結果如下:


到此這篇關于Python實現(xiàn)Web服務器(FastAPI的文章就介紹到這了,更多相關Python Web服務器內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
tensorflow實現(xiàn)二維平面模擬三維數(shù)據(jù)教程
今天小編就為大家分享一篇tensorflow實現(xiàn)二維平面模擬三維數(shù)據(jù)教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
利用Python統(tǒng)計Jira數(shù)據(jù)并可視化
目前公司使用 Jira 作為項目管理工具,在每一次迭代完成后的復盤會上,我們都需要針對本次迭代的 Bug 進行數(shù)據(jù)統(tǒng)計,以幫助管理層能更直觀的了解研發(fā)的代碼質量。本篇文章將介紹如何利用統(tǒng)計 Jira 數(shù)據(jù),并進行可視化,需要的可以參考一下2022-07-07
詳解python架構?PyNeuraLogic超越Transformers
這篇文章主要為大家介紹了python使用?PyNeuraLogic超越Transformers示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03
python如何利用paramiko執(zhí)行服務器命令
這篇文章主要介紹了python如何利用paramiko執(zhí)行服務器命令,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-11-11
python中實現(xiàn)根據(jù)坐標點位置求方位角
這篇文章主要介紹了python中實現(xiàn)根據(jù)坐標點位置求方位角方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08

