기본 콘텐츠로 건너뛰기

FastAPI 개발환경 구성하기

Pure Windows는 적합하지 않을 것 같아  WSL에서 Docker 기반으로 환경을 구성하고

Docker Desktop 설치후

WSL 환경에서 Docker image 로 my-fastapi-app 를 준비함

docker build -t my-fastapi-app . "

 

WSL 환경에서 Docker container 로 fastapi-app 로 데몬으로 준비, 포트 8000 연결조건

docker run -d -p 8000:8000 --name fastapi-app my-fastapi-app


WSL 환경에서 Docker containter를 종료시 삭제조건과 app폴더를 연결하는 조건 
docker run -d -p 8000:8000 --rm -v $(pwd):/app my-fastapi-app

WSL 환경에서 Docker containter에게 이름  fastapi-app 지정하는 조건

docker run -d -p 8000:8000 -v $(pwd):/app --name fastapi-app my-fastapi-app


WSL 에서 Docker container fastapi-app 에 연결하기

docker exec -it fastapi-app /bin/bash  

# 1. 경량 Python 베이스 이미지 사용
FROM python:3.11-slim

# 2. 환경 변수 설정 (버퍼링 비활성화, UTF-8 지원)
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1

# 3. 작업 디렉터리 생성 및 설정
WORKDIR /app

# 4. 의존성 설치를 위한 requirements.txt 복사
COPY requirements.txt .

# 5. 패키지 설치 (캐시 최소화 및 빌드 최적화)
RUN pip install --no-cache-dir --upgrade pip \
    && pip install --no-cache-dir -r requirements.txt

# 6. 애플리케이션 코드 복사
COPY . .

# 7. FastAPI 서버 실행
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]



개발과 테스트에 필요한 패키지 설치 (requirements)

fastapi
uvicorn
httpie
requests
httpx
black
pytest

FastAPI hello world
from fastapi import FastAPI

app = FastAPI()
@app.get("/hi")
def say_hello():
    return {"message": "Hello, World"}

연습코드
https://github.com/johlim/FastAPI


AWS 에서 운용하는 EC2 들은 최근 python version을 지원하지 않는 경우가 많다.
경험적으로는 3.8이 기본이고 3.9까지는 수동 설치가 가능하므로 
python 3.9 까지 지원하는 문법을 사용하는것이 호환성을 개선할수 있다.



자동테스트

schemathesis run http://localhost:8000/openapi.json --experimental=openapi-3.1

결과
---
Performed checks:
    not_a_server_error                    1408 / 1420 passed          FAILED

WARNINGS:
  - Most of the responses from `GET /user/token` have a 401 status code. Did you specify proper API credentials?
  - Most of the responses from `GET /auth/who` have a 401 status code. Did you specify proper API credentials?
  - `POST /explorer` returned only 4xx responses during unit tests. Check base URL or adjust data generation settings
  - `GET /explorer/{name}/` returned only 4xx responses during unit tests. Check base URL or adjust data generation settings
  - `DELETE /explorer/{name}/` returned only 4xx responses during unit tests. Check base URL or adjust data generation settings
  - `GET /explorer/{name}` returned only 4xx responses during unit tests. Check base URL or adjust data generation settings
  - `DELETE /explorer/{name}` returned only 4xx responses during unit tests. Check base URL or adjust data generation settings

Experimental Features:
  - OpenAPI 3.1: Support for response validation
    Feedback: https://github.com/schemathesis/schemathesis/discussions/1822

Your feedback is crucial for experimental features. Please visit the provided URL(s) to share your thoughts.

Note: Use the 'X-Schemathesis-TestCaseId' header to correlate test case ids from failure messages with server logs for debugging.

Note: To replicate these test failures, rerun with `--hypothesis-seed=202434289134074871147673993360901731981`

======================================================================== 22 passed, 6 failed in 73.65s =========================================================================
--

댓글

이 블로그의 인기 게시물

DELL의 새게이밍 노트북, Inspiron 15 7000 Gaming, Dual Display 문제

Dell New 게이밍노트북 7567  I7 Notebook http://www.dell.com/kr/p/inspiron-15-7567-laptop/pd?ref=PD_OC 7th Generation Intel® Core™ i7 프로세서 8GB 메모리 1TB 하드 드라이브 + 128GB 솔리드 스테이트 드라이브 NVIDIA® GeForce® GTX 1050 Ti (4GB GDDR5 그래픽 메모리 포함) 상세 사양 리눅스 개발환경이 필요해서 여러대 구매한 노트북입니다. 기본적으로 ubuntu 16.04 가 설치되어 있는데, 필요한 개발환경이 ubuntu 이고 별도의 windows 개발용 PC가 있기 때문에 구매를 결정하게 되었습니다. Slim하지 않지만 I7 HQ CPU와 1050TI spec 이 결정하는데 주요했고, 받은 후에 빌드환경 구축후 8 thread compile을 만끽하던중 치명적인 문제를 Display쪽 문제를 발견하고, Dell express 쪽과 전화통화도 하고 문의 메일도 보내서 지원을 받고(진행)중입니다. 추가 :  시간낭비하지 말라고 중간에 업데이트합니다.  해결되었고, 해결방법은  Windows 을 설치한 후 Fn+F8을 눌러서 모드를 확장모드를 선택합니다. 디스플레이 설정이나 드라이버 재설치 같은 방법으로는 조정이 불가능했습니다. --------------------------------------------------------------------- 요즘 다들 Dual monitor 환경일텐데, Dual Monitor를 복제형태로만 지원을 합니다. 14.04 설치후 업데이트시 375.66 Driver가 설치됩니다. nVidia driver가 설치되었으나, 모니터 인식에 문제가 있어서 해상도 확장설정자체를 할 수 없습니다. 기본 ubuntu라서 driver 문제인가 확인하기 위해서 우분투 64bit 환경 NVIDIA...

llama 계열 gguf 제공되는 경우 가져와서 사용하는 예제

llama 계열의 모델이 친절하게 gguf 형태로 제공되는 경우 어떻게 다운받고 어떻게 ollama에 추가하는지 예전에 gguf 파일을 등록하는 유튜브 강의를 보고 메모해두것을 기반으로 2024년 12월31일 추운 겨울 밤 기억을 백업해 봅니다 수동으로 작성한 것은 지우고 copilot으로 포맷을 정리해서 업데이트합니다. Bllossom/llama-3.2-Korean-Bllossom-3B-gguf-Q4_K_M 한국어 모델 추가하기 시작 : MS Copilot과의 질의응답 중 llama 3.2 기반의 한국어 학습 모델을 발견. 현재 사용 모델 : EEVE-Korean-10.8B (약 7.7 GB) 모델 사용 중. llama 3.2 기반 한국어 모델 소개 : 모델 설명 링크 gguf 파일 다운로드 링크 deepseek-ai/DeepSeek-R1-Distill-Qwen-7B  기반 한국어 모델 소개 : 모델 설명 링크 gguf 파일 다운로드 링크 모델 설정 파일 (Modelfile) : FROM llama-3.2-Korean-Bllossom-3B-gguf-Q4_K_M.gguf PARAMETER temperature 0.6 PARAMETER top_p 0.9 TEMPLATE """<|start_header_id|>system<|end_header_id|> Cutting Knowledge Date : December 2023 {{ if .System }}{{ .System }} {{- end }} {{- if .Tools }} When you receive a tool call response, use the output to format an answer to the orginal user question. You are a helpful assistant with tool calling capabilities. {{- end }} <|eot_id|> {{- range $i , $_ := .Messa...

우분투에서 성가신 자동 실행 처리

우분투운서비스는 종료된지 예전인데 script에 남아 있어서 항상 실행된다 apt-get 패키지가 제거되어도 etc/xdg/autostart 폴더에서 삭제해야 실행되지 않는다. /etc/xdg/autostart$ ls at-spi-dbus-bus.desktop              gnome-settings-daemon.desktop                print-applet.desktop bluetooth-applet-unity.desktop       gnome-sound-applet.desktop                   pulseaudio-kde.desktop bluetooth-applet.desktop             gnome-user-share.desktop                     pulseaudio.desktop deja-dup-monitor.desktop             gsettings-data-convert.desktop               telepathy-indicator.desktop gdu-notification-daemon.desktop      gwibber.desktop                             ...