FastAPI Todo 應用程式:設定您的 Todo 應用程式項目

WBOY
發布: 2024-07-26 12:16:51
原創
1058 人瀏覽過

FastAPI Todo App: Setting Up Your Todo App Project

FastAPI 入門:設定您的 Todo 應用程式項目

一、簡介

在本部落格系列中,讀者將學習如何使用 FastAPI 建立待辦事項應用程式。本系列將逐步指導您使用 FastAPI(一種現代高效能 Python Web 框架)從頭開始建立待辦事項應用程式。內容涵蓋從設定開發環境到部署應用程式的所有內容。在本系列結束時,讀者將創建自己的待辦事項應用程式並牢牢掌握 FastAPI。

該系列中的每篇文章都將重點放在開發過程的特定方面,提供清晰的解釋和實用的程式碼範例。目標是讓讀者掌握使用 FastAPI 建立 Web 應用程式所需的知識和技能。無論您是想要學習 Web 開發的初學者,還是探索 FastAPI 的經驗豐富的開發人員,本系列都旨在提供寶貴的見解和實踐經驗。

第一篇文章將介紹 FastAPI,幫助您設定開發環境並建立 FastAPI 應用程式。

Todo_Part1 目錄中的部落格程式碼:GitHub - jamesbmour/blog_tutorials

二. FastAPI簡介及其好處

A.什麼是FastAPI?

FastAPI 是一個現代、快速(高效能)的 Web 框架,用於基於標準 Python 類型提示使用 Python 3.6+ 建立 API。它被設計為易於使用、快速編碼、可用於生產,並且基於最新的 Python 功能。

B. FastAPI 的主要特點

  1. 快速效能:FastAPI 建立在用於 Web 部分的 Starlette 和用於資料部分的 Pydantic 之上,使其成為可用的最快的 Python 框架之一。
  2. 易於使用和學習:FastAPI 具有直覺的設計和優秀的文檔,對開發人員非常友好。
  3. 自動 API 文件:FastAPI 會根據您的程式碼自動產生互動式 API 文件(使用 Swagger UI 和 ReDoc)。
  4. 型別檢查與編輯器支援:FastAPI 利用 Python 的型別提示,透過自動完成和錯誤偵測提供優異的編輯器支援。

C. 與其他Python Web框架的比較

與 Flask 或 Django 等其他流行的 Python Web 框架相比,FastAPI 提供:

  • 更好的表現
  • 內建API文件
  • 更輕鬆地處理請求/回應驗證
  • 原生非同步支援

D. 為什麼FastAPI適合建構Todo App

對於我們的 Todo 應用程序,FastAPI 是一個絕佳的選擇,因為:

  • 它允許快速開發我們的 API 端點。
  • 它提供自動請求驗證,減少我們需要編寫的程式碼量。
  • 內建的 API 文件將使我們的端點測試變得容易。
  • 其高效能將確保我們的應用程式即使在成長時也能保持回應能力。

三.設定開發環境

A. 安裝 Python (3.7+)

確保您安裝了 Python 3.7 或更高版本。您可以從 python.org 下載它。

B. 建立虛擬環境

最佳實務是為 Python 專案使用虛擬環境。建立方法如下:

  1. 使用 venv:
python -m venv todo-env
source todo-env/bin/activate  # On Windows, use `todo-env\Scripts\activate`
登入後複製
  1. 使用 conda(替代方案):
conda create --name todo-env python=3.9
conda activate todo-env
登入後複製
  1. 安裝詩歌
poetry install  
# activate the virtual environment  
poetry shell  
登入後複製

C. 安裝FastAPI及其相依性

現在,讓我們安裝 FastAPI 和 Uvicorn(ASGI 伺服器):

pip install fastapi uvicorn
登入後複製

四.建立基本的 FastAPI 應用程式

A. 撰寫第一個 FastAPI 腳本

建立一個名為main.py的新檔案並新增以下程式碼:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello, FastAPI!"}
登入後複製

B.程式碼結構說明

  • 我們從 fastapi 模組匯入 FastAPI。
  • 我們建立一個名為 app 的 FastAPI 實例。
  • 我們使用 @app.get("/") 裝飾器定義一個路由,它告訴 FastAPI 下面的函數處理對根 URL ("/") 的 GET 請求。
  • async def root(): 函數是我們的路由處理程序,它傳回一個 JSON 物件。

C. 使用 Uvicorn 運行 FastAPI 應用程式

要執行應用程序,請使用以下命令:

uvicorn main:app --reload
登入後複製

此指令告訴 Uvicorn:

  • Look for an app object in main.py
  • Run it as an ASGI application
  • Watch for file changes and reload the server (--reload option)

D. Accessing the automatic API documentation (Swagger UI)

Once your server is running, you can access the automatic API documentation by navigating to http://127.0.0.1:8000/docs in your web browser.

V. Defining the project structure

A. Creating a new directory for the Todo App

Create a new directory for your project:

mkdir fastapi-todo-app
cd fastapi-todo-app
登入後複製

B. Setting up a basic project structure

Create the following files in your project directory:

  1. main.py (entry point)
  2. requirements.txt
  3. .gitignore

C. Explaining the purpose of each file and directory

  • main.py: This is the main entry point of our application where we define our FastAPI app and routes.
  • requirements.txt: This file lists all the Python packages required for our project.
  • .gitignore: This file specifies which files and directories should be ignored by Git version control.

Add the following to your requirements.txt:

fastapi
uvicorn
登入後複製

And add this to your .gitignore:

__pycache__
*.pyc
todo-env/
登入後複製

VI. Implementing a simple "Hello, World!" endpoint

A. Creating a root endpoint

We've already created a root endpoint in our main.py. Let's modify it slightly:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Welcome to the Todo App!"}
登入後複製

B. Returning a JSON response

FastAPI automatically converts the dictionary we return into a JSON response.

C. Testing the endpoint using a web browser

Run your server with uvicorn main:app --reload, then navigate to http://127.0.0.1:8000 in your web browser. You should see the JSON response.

D. Using the interactive API documentation

Navigate to http://127.0.0.1:8000/docs to see the Swagger UI documentation for your API. You can test your endpoint directly from this interface.

VII. Next steps

In the upcoming blog post, we will explore FastAPI in more detail by developing the fundamental features of our Todo App. We will establish endpoints for adding, retrieving, updating, and deleting todos. As an exercise, you can add a new endpoint that provides the current date and time when accessed.

@app.get("/current-time")  
async def get_current_time():  
    current_time = datetime.now()  
    return {  
        "current_date": current_time.strftime("%Y-%m-%d"),  
        "current_time": current_time.strftime("%H:%M:%S"),  
        "timezone": current_time.astimezone().tzname()  
    }
登入後複製

VIII. Conclusion

Congratulations! You've successfully set up your development environment, created your first FastAPI application, and learned about the basic structure of a FastAPI project.

We've covered a lot of ground in this post. We've discussed what FastAPI is and why it's a great choice for our Todo App. We've also written our first endpoint and run our application.

In the next post, we'll start building the core functionality of our Todo App. Stay tuned, and happy coding!

If you would like to support me or buy me a beer feel free to join my Patreon jamesbmour

以上是FastAPI Todo 應用程式:設定您的 Todo 應用程式項目的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!