FastAPI Todo アプリ: Todo アプリ プロジェクトのセットアップ

WBOY
リリース: 2024-07-26 12:16:51
オリジナル
1058 人が閲覧しました

FastAPI Todo App: Setting Up Your Todo App Project

FastAPI の入門: Todo アプリ プロジェクトのセットアップ

I. はじめに

このブログ シリーズでは、読者は FastAPI を使用して To-Do アプリを構築する方法を学びます。このシリーズでは、最新の高性能 Python Web フレームワークである FastAPI を使用して To-Do アプリケーションを最初から作成する方法を段階的にガイドします。内容は開発環境の構築からアプリのデプロイまでを網羅しています。シリーズの終わりまでに、読者は独自の To-Do アプリを作成し、FastAPI をしっかりと理解できるようになります。

シリーズの各投稿では、開発プロセスの特定の側面に焦点を当て、明確な説明と実践的なコード例を提供します。目標は、FastAPI を使用して Web アプリケーションを構築するために必要な知識とスキルを読者に提供することです。 Web 開発を学ぼうとしている初心者でも、FastAPI を検討している経験豊富な開発者でも、このシリーズは貴重な洞察と実践的な経験を提供することを目的としています。

最初の投稿では、開発環境のセットアップと FastAPI アプリケーションの作成に役立つ FastAPI を紹介します。

Todo_Part1 ディレクトリのブログ コード: GitHub - jamesbmour/blog_tutorials

II. FastAPI とその利点の概要

A. FastAPI とは何ですか?

FastAPI は、標準の Python 型ヒントに基づいて Python 3.6 以降で API を構築するための最新の高速 (高性能) Web フレームワークです。使いやすく、コーディングが速く、すぐに実稼働できるように設計されており、最新の Python 機能に基づいています。

B. FastAPI の主な機能

  1. 高速パフォーマンス: FastAPI は、Web パーツ用の Starlette とデータ パーツ用の Pydantic 上に構築されており、利用可能な Python フレームワークの中で最も高速なものの 1 つとなっています。
  2. 使いやすく、学習も簡単: FastAPI は、直感的なデザインと優れたドキュメントにより、非常に開発者にとって使いやすいものです。
  3. 自動 API ドキュメント: FastAPI は、コードに基づいて対話型 API ドキュメント (Swagger UI と ReDoc を使用) を自動的に生成します。
  4. 型チェックとエディターのサポート: FastAPI は Python の型ヒントを活用し、オートコンプリートとエラー検出による優れたエディター サポートを提供します。

C. 他の Python Web フレームワークとの比較

Flask や Django などの他の人気のある Python Web フレームワークと比較して、FastAPI は以下を提供します:

  • パフォーマンスの向上
  • 組み込み API ドキュメント
  • リクエスト/レスポンス検証の処理が簡単になりました
  • ネイティブ非同期サポート

D. FastAPI が Todo アプリの構築に適している理由

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
ログイン後にコピー

IV.基本的な 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("/") デコレーターを使用してルートを定義し、以下の関数がルート URL ("/") への GET リクエストを処理することを FastAPI に伝えます。
  • 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 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!