原創 菜鳥童靴 菜鳥童靴 4天前
fastapi介紹
FastAPI 文檔 https://fastapi.tiangolo.com/
FastApi 是一個異步 Web 框架,它的速度非常非常非常快。遠遠超過 Flask。速度可以匹敵 Golang 寫的接口
有官方的docker 鏡像,方便用docker部署
安裝:
1、安裝 FastAPI 模塊
pip install fastapi
2、安裝 Uvicorn 模塊(生產環境使用的ASGI服務器)
Uvicorn是基於uvloop和httptools構建的閃電般快速的ASGI服務器
pip install uvicorn
今天在這裏簡單介紹,我們可以使用fastapi 在做些什麼?
應用場景一
需求:
實現一個本地的文件分享服務,
(1)服務要求,多人使用不衝突
(2)網絡服務要穩定
(3)使用者,只知道自己要下載的文件,其他一概不知,具有安全性
fastapi 基於starlette 開發。而 starlette裏面有一個返回類型叫做FileResponse
。使用它,可以非常方便地返回文件。
這裏藉助一個庫
pip install aiofiles
我們來看看代碼。
首先建立一個test.py文件,並分享當前目錄下的文件內容a.mp4
import os
from fastapi import FastAPI
from starlette.responses import FileResponse
app = FastAPI()
@app.get('/download/{filename}')
def get_record(filename: str):
path = os.path.join(os.getcwd(), filename)
print(path)
if not os.path.exists(path):
return {'success': False, 'msg': '文件不存在!'}
response = FileResponse(path)
return response
if __name__ == '__main__':
command = "uvicorn test:app --host 0.0.0.0 --port 8888"
os.system(command)
運行程序,開啓服務
分享文件夾下的文件有:
請求服務,開啓下載我們想要的文件:
或者:
總結:
這樣,你想分享具體哪個文件,你就構造一個 URL:http://ip:8888/download/文件名
發給別人。別人直接訪問這個 URL 就能來下載對應的文件了。只要對方不知道其他文件的文件名,就無法看到或者下載其他文件。
如果想更安全,你還可以給每個文件做一個單獨的文件編號,把編號-地址對應關係存放在數據庫中。用戶請求的時候,傳入的是文件編號,你從數據庫查出文件的真實路徑再通過FileResponse
返回。
總結參考來源於,網易青南大佬的文章,在此做一個學習記錄
應用場景二
接口的實現:
(1)創建 main.py 文件
import os
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
(2)啓動ASGI Server
uvicorn main:app --reload
該命令uvicorn main:app指的是:
main:文件main.py(Python“模塊”)。
app:main.py在線內創建的對象app = FastAPI()。
--reload:更改代碼後使服務器重新啓動。這樣做是爲了開發
(3)完整代碼
import os
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
if __name__ == '__main__':
command = "uvicorn test:app --host 0.0.0.0 --port 8888 --reload"
os.system(command)
(4)接口請求
(5)查看接口文檔,有兩種接口文檔
http://localhost:8888/docs
http://localhost:8888/redoc
(6)
再看如下的代碼分析:
import os
from fastapi import FastAPI
app = FastAPI()
@app.get('/query/{uid}')
def query(uid: int):
msg = f'你查詢的 uid 爲:{uid}'
return {'success': True, 'msg': msg}
if __name__ == '__main__':
command = "uvicorn test:app --host 0.0.0.0 --port 8888 --reload"
os.system(command)
在頁面請求後:
當我們傳遞字符串時:
當 query 後面的參數不是整數時,正常報錯了。
更改需求
有一個非常簡單的需求:編寫一個 HTTP 接口,使用 POST 方式發送一個 JSON 字符串,接口裏面讀取發送上來的參數,對其中某個參數進行處理,並返回。我們需要手動驗證用戶 POST 提交上來的數據是什麼格式的,字段對不對。
但使用 FastApi 的時候,我們只需要類型標註就能解決所有問題。首先我們導入from pydantic import BaseModel
,然後繼承BaseModel
實現我們允許 POST 方法提交上來的數據字段和格式:
import os
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class People(BaseModel):
name: str
age: int
address: str
salary: float
@app.post('/insert')
def insert(people: People):
age_after_10_years = people.age + 10
msg = f'此人名字叫做:{people.name},十年後此人年齡:{age_after_10_years}'
return {'success': True, 'msg': msg}
if __name__ == '__main__':
command = "uvicorn test:app --host 0.0.0.0 --port 8888 --reload"
os.system(command)
insert
函數的參數people
通過類型標註指定爲People
類型。
當我們使用 POST 方式提交數據時,FastApi 自動會以People
中定義的字段爲基準來校驗數據,發現不對就返回報錯信息。
驗證代碼:
import requests
people = {"name": "MrYang", "age": 26, "address": "bejing", "salary": 1111}
url = "http://localhost:8888/insert"
result = requests.post(url, headers={}, json=people).json()
print(result)
測試結果:
文章首發於微信公衆號菜鳥童靴,不定期更新,如有需要後臺加微信