[전체틀]
- backend: FastAPI
- fronend: Stelve사용
[생성과정]
- myapi폴더 만들기(프로젝트 폴더)
- 가상환경 만들기
- node.js 설치 > vscode 재실행
- 설치: https://nodejs.org/en
- 터미널에서 node -v 입력 버젼 나오면 정상 설치 된 것
- npm create vite@latest frontend -- -- template svelte 입력 아래 사진 나오면 성공
- 아래 오류 나오면 방화벽 문제: npm config set strict-ssl false -g 이걸로 해결
(venv) D:\webproject\myapi>npm create vite@latest frontend -- -- template svelte
npm ERR! code SELF_SIGNED_CERT_IN_CHAIN
npm ERR! errno SELF_SIGNED_CERT_IN_CHAIN
npm ERR! request to https://registry.npmjs.org/create-vite failed, reason: self-signed certificate in certificate chain
Node.js — Run JavaScript Everywhere
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.
nodejs.org
- cd frontend를 통해 폴더로 이동 > npm install
[backend 설치 및 구동]
1. 설치
- FastAPI설치: pip install fastapi
- 비동기 서버설치: pip install "uvicorn[standard]"(fastapi설치하면 보통 자동으로 설치됨)
- Uvicorn: 비동기 호출을 지원하는 파이썬용 웹 서버 -> fastAPI는 비동기 호출을 지원하기 때문에 uvicorn 별도 설치
2. 구동
- main.py파일 만들어 해당 내용 입력
from fastapi import FastAPI
app = FastAPI()
@app.get('/hello')
def hello():
return {"message": "hello"}
- 서버실행(터미널에 입력): uvicorn main:app --reload
- main: main.py
- app: app객체
- --reload: 프로그램 변경시 서버 재시작 없이 내용 반영(debug=True와 유사)
- 터미널에 열리는 포트확인(8000)
- 127.0.0.1:8000/docs로 접속: main.py에 작성한 api가 등록되어 나타남 gui로 동작하는지 확인 가
- 127.0.0.1:8000/redoc로 접속: main.py에 작성한 api를 읽기만 하는것
[frontend 구동: svelte for VScode extention 설치]
1. 자바스크립트 타입 체크 false
- jsconfig.json파일 변경
{
"compilerOptions": {
"moduleResolution": "bundler",
"target": "ESNext",
"module": "ESNext",
// ......생략......
/**
* Typecheck JS in `.svelte` and `.js` files by default.
* Disable this if you'd like to use dynamic types.
*/
"checkJs": false // 이부분 false로 변경
},
/**
* Use global.d.ts instead of compilerOptions.types
* to avoid limiting type declarations.
*/
"include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"]
}
2. frontend 터미널에서 npm run dev 입력 및 실행(localhost:5173)
3. App.svelte, app.css 내용 모두 제거 후 App.svelte에 hello만 작성
[backend와 frontend 연결]
- frontend/App.svelte파일 수정
<script>
// message 변수 할당
let message;
// fastapi의 api를 호출하여 받은 값을 message에 할당
fetch("http://127.0.0.1:8000/hello").then((response) => {
response.json().then((json) => {
message = json.message;
})
})
</script>
// {}를 이용해 변수의 값 나타냄
<h1> {message} </h1>
- hello가 안나오고 undefined가 나옴: 개발자모드에서 보면 CORS policy에 맞지 않는다고 나와있음
- 해결을 위해 fastapi의 main.py파일 수정(frontend의 주소 예외처리)
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware //추가
app = FastAPI()
//예외처리할 주소
origins = [
"http://localhost:5173",
]
//추가
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/hello")
def hello():
return {"message": "hello"}
@app.get("/home")
def home():
return {'home': 'sweethome'}
'FrameWork > FastAPI' 카테고리의 다른 글
Pydantic & 스키마 (0) | 2024.05.26 |
---|---|
db커넥션 관리 (0) | 2024.05.25 |
Router (0) | 2024.05.25 |
database 구축 (0) | 2024.05.24 |
프로젝트 구조 (0) | 2024.05.24 |