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 웹 프레임워크인 FastAPI를 사용하여 처음부터 To-Do 애플리케이션을 만드는 과정을 단계별로 안내합니다. 콘텐츠는 개발 환경 설정부터 앱 배포까지 모든 것을 다룹니다. 시리즈가 끝날 무렵 독자들은 자신만의 To-Do 앱을 만들고 FastAPI에 대해 확실히 이해하게 될 것입니다.

시리즈의 각 게시물은 개발 프로세스의 특정 측면에 초점을 맞춰 명확한 설명과 실용적인 코드 예제를 제공합니다. 목표는 FastAPI를 사용하여 웹 애플리케이션을 구축하는 데 필요한 지식과 기술을 독자에게 제공하는 것입니다. 웹 개발을 배우려는 초보자이든 FastAPI를 탐색하는 숙련된 개발자이든 이 시리즈는 귀중한 통찰력과 실무 경험을 제공하는 것을 목표로 합니다.

첫 번째 게시물에서는 개발 환경을 설정하고 FastAPI 애플리케이션을 만드는 데 도움이 되는 FastAPI를 소개합니다.

Todo_Part1 디렉토리의 블로그 코드: GitHub - jamesbmour/blog_tutorials

II. FastAPI 소개 및 이점

A. FastAPI란 무엇입니까?

FastAPI는 표준 Python 유형 힌트를 기반으로 Python 3.6+로 API를 구축하기 위한 현대적이고 빠른(고성능) 웹 프레임워크입니다. 사용하기 쉽고, 빠르게 코딩할 수 있으며, 프로덕션에 바로 사용할 수 있고, 최신 Python 기능을 기반으로 설계되었습니다.

B. FastAPI의 주요 기능

  1. 빠른 성능: FastAPI는 웹 파트용 Starlette와 데이터 파트용 Pydantic을 기반으로 구축되어 사용 가능한 가장 빠른 Python 프레임워크 중 하나입니다.
  2. 사용하기 쉽고 배우기: FastAPI는 직관적인 디자인과 뛰어난 문서 기능을 갖추고 있어 매우 개발자 친화적입니다.
  3. 자동 API 문서: FastAPI는 코드를 기반으로 (Swagger UI 및 ReDoc 사용) 대화형 API 문서를 자동으로 생성합니다.
  4. 유형 확인 및 편집기 지원: FastAPI는 Python의 유형 힌트를 활용하여 자동 완성 및 오류 감지 기능을 갖춘 탁월한 편집기 지원을 제공합니다.

C. 다른 Python 웹 프레임워크와의 비교

Flask 또는 Django와 같은 다른 인기 있는 Python 웹 프레임워크와 비교하여 FastAPI는 다음을 제공합니다.

  • 더 나은 성능
  • 내장 API 문서
  • 요청/응답 검증 처리가 더 쉬워졌습니다
  • 기본 비동기 지원

D. FastAPI가 Todo 앱 구축에 적합한 이유

Todo 앱의 경우 FastAPI는 다음과 같은 이유로 탁월한 선택입니다.

  • API 엔드포인트를 빠르게 개발할 수 있습니다.
  • 자동 요청 확인 기능을 제공하여 작성해야 하는 코드의 양을 줄여줍니다.
  • 내장된 API 문서를 통해 엔드포인트를 쉽게 테스트할 수 있습니다.
  • 뛰어난 성능 덕분에 앱이 성장하는 동안에도 응답성을 유지할 수 있습니다.

III. 개발 환경 설정

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 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!