# 自然人眼中的 FastAPI 原本在研究 [自然人眼中的 thread (task manager)](/hxvgsCEET--MohA08TB1mA) 做簡單的任務排程,但是考量專案( AI翻譯文件),使用者需要有 frontend 界面操作,因此開始研究 backend 的 API 接口,這邊就選擇近年來熱門的 Python 框架 FastAPI 作為開頭! ## 基本使用 事實上有非常多元的入門教學可以參考,如 [Fast API 入門筆記](https://minglunwu.com/notes/2021/fast_api_note_1.html/)等等,但是主要還是以[官網](https://fastapi.tiangolo.com/)為主學習,我的環境是 uv ,所以在啟動服務時要注意 [using uv with FastAPI](https://docs.astral.sh/uv/guides/integration/fastapi/)。 基本舉例程式碼: ```python! from typing import Union from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"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} ``` ### 靜態檔案操作 稍稍進階一點的功能,使用 `StaticFiles` [package](https://fastapi.tiangolo.com/tutorial/static-files/) 將資料夾 mount 入,讓這個資料夾內部檔案可以透過 API 給用戶端上傳與下載檔案,不過需要是已經存在的資料夾以及靜態資料。 ## 實現技術 FastAPI 之所以熱門是因為有 ASGI (Asynchronous Server Gateway Interface),而它也被稱為 WSGI 繼承者(successor)的規範,能夠同時支援 HTTP 與 WebSocket 這兩種截然不同的協定,之後會在展開介紹 ASGI 以及 WSGI 這兩種 interface。 ### HTTP Method FastAPI 在定義路徑時,會透過 decorator(裝飾子)一併定義 API 可提供的 HTTP Method: `@app.post()` : Post 方法 `@app.get()` : Get 方法 `@app.put()` : Put 方法 `@app.delete()` : Delete 方法 請參考詳細的 [HTTP Method](https://realnewbie.com/basic-concent/what-is-http-method/) 資料,另外下方簡單講解 decorator 的說明,詳細請見整理在 [advanced python](https://hackmd.io/XS3jwReXTuui05hFLx7aGw) ~ :::info Python 中的 Decorator 可以在不修改原本函式內容的前提下,額外包入另一個函式! ```python! def decorator(func): def wrapper(): print("裝飾前") func() print("裝飾後") return wrapper @decorator def say_hi(): print("Hi!") say_hi() ``` ::: ### WebSocket FastAPI 其中一個特點是除了傳統的 HTTP 技術也可以支援 WebSocket,WebSocket 是一種長期連線技術允許多次的客戶端與伺服器端互動事件發生,這代表應用需要能夠處理持續的雙向通訊,而不僅僅是處理單一的要求和回應。 而為何 FastAPI 可以支援兩種不同的協定呢?答案就是跟 ASGI (Asynchronous Server Gateway Interface) 有密切的關係了! [【Web微知識系列】雙向溝通的技術,什麼是Websocket?](https://vocus.cc/article/627280c5fd89780001c71e35) ### CGI, WSGI and ASGI 想要深入了解 ASGI 必須先知道 CGI, WSGI,展開討論會是很大的篇幅,附上參考資料可以深入挖掘(還沒搞懂⚠️ 方便日後複習✅) [理解 Python 後端技術:從 CGI 談到 WSGI, uWSGI 與 uwsgi](https://myapollo.com.tw/blog/python-backend-cgi-wsgi-uwsgi-explanations/) [理解 Python 後端技術: ASGI (Asynchronous Server Gateway Interface) — WSGI 的繼承者](https://myapollo.com.tw/blog/python-asgi-introduction/)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up