FastAPI - ์„ค์น˜

2023. 7. 31. 09:38ใ†๊ฐœ๋ฐœ/Python

728x90
๋ฐ˜์‘ํ˜•
๐Ÿ’ก ์ค€๋น„๋ฌผ - VM, Linux, (CentOS or Ubuntu)
Python3 ์ถœ์ฒ˜ : https://phsun102.tistory.com/62?category=891189,
https://chacha95.github.io/2021-01-16-python6/

์„ค์น˜

์„ค์น˜์ „ pip3 ์„ค์น˜

  • pip3 : Python3 ๋ฒ„์ „ ํŒจํ‚ค์ง€ ๋งค๋‹ˆ์ €
  • CentOS ๊ณ„์—ด
yum install python-pip3
  • Ubuntu ๊ณ„์—ด
apt-get install python-pip3

์„ฑ๊ณต์‹œ

  • fastapi ์„ค์น˜
pip3 install fastapi # FastAPI ์‚ฌ์šฉ์„ ์œ„ํ•œ ์„ค์น˜

์‹คํŒจ์‹œ

  • pip ์ง์ ‘ ์„ค์น˜
curl <https://bootstrap.pypa.io/pip/3.6/get-pip.py> -o get-pip.py
python3 get-pip.py

Uvicorn ์„ค์น˜

Uvicorn ์†Œ๊ฐœ

  • Uvicorn ์„ค์น˜
pip3 install uvicorn # Python ์„œ๋ฒ„์‹คํ–‰๊ธฐ

ํ…Œ์ŠคํŠธ

Python ์ž‘์„ฑ

  • python main.py ์†Œ์Šค ์ž‘์„ฑ
# main.py

from fastapi import FastAPI # FastAPI ๋ชจ๋“ˆ ๊ฐ€์ ธ์˜ค๊ธฐ

app = FastAPI() # ๊ฐ์ฒด ์ƒ์„ฑ

@app.get("/") # Route Path
def test_index():
	
    # Json ํƒ€์ž…์œผ๋กœ ๊ฐ’ ๋ฐ˜ํ™˜
    return {
	    "Python": "Framework",
	}
    
@app.get("/something")
def something():
    return {
        "Something": "Page",
    }
  • ๊ฐ„๋‹จํ•œ ํ…Œ์ŠคํŠธ ๋กœ์ปฌ ํ˜ธ์ŠคํŠธ๋กœ ์ ‘๊ทผ์‹œ
    • index ํŽ˜์ด์ง€๋กœ {"Python":"Framework"} ์ถœ๋ ฅ
    • /something ํŽ˜์ด์ง€ {"Something":"Page"} ์ถœ๋ ฅ

Uvicorn ๋ช…๋ น์–ด ์‹คํ–‰

uvicorn main:app --reload --host 0.0.0.0 --port 8000 # 8000 ํฌํŠธ์˜ ์›น์„œ๋ฒ„๋ฅผ ๊ฐ€๋™
  • uvicorn : python ์„œ๋ฒ„ ์‹คํ–‰์„ ์œ„ํ•ด ํ•„์š”ํ•œ ๊ธฐ๋ณธ ๋ช…๋ น์–ด
  • main : ์‹คํ–‰ํ•  ์ดˆ๊ธฐ python ํŒŒ์ผ ์ด๋ฆ„
  • app : FastApi() ๋ชจ๋“ˆ์„ ํ•ญ๋‹นํ•œ ๊ฐ์ฒด๋ช…
  • reload : ์†Œ์Šค ์ฝ”๋“œ๊ฐ€ ๋ณ€๊ฒฝ๋˜์—ˆ์„๋•Œ ์ž๋™ ์žฌ์‹œ์ž‘ ์˜ต์…˜
  • host : ๋ชจ๋“  ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•ด 0.0.0.0
  • port : ์›น์„œ๋ฒ„ ํฌํŠธ ํ• ๋‹น
  • ์‹คํ–‰ ๊ฒฐ๊ณผ
INFO:     Will watch for changes in these directories: ['/home/haay/fastapi']
INFO:     Uvicorn running on <http://127.0.0.1:8000> (Press CTRL+C to quit)
INFO:     Started reloader process [19228] using statreload
INFO:     Started server process [19230]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Web Server ์ ‘๊ทผ

curl localhost:8000 # index ํŽ˜์ด์ง€ ์ ‘๊ทผ
{"Python":"Framework"}
curl localhost:8000/something # something ํŽ˜์ด์ง€ ์ ‘๊ทผ
{"Something":"Page"}

API ๋ฌธ์„œํ™”

Docs ๊ธฐ๋Šฅ์„ ์ง€์›ํ•˜์—ฌ ๋“ฑ๋ก๋œ API๋ฅผ ๋ฌธ์„œํ™”๋œ UI๋กœ ํ™•์ธ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

  • ์ ‘์† ๋ฐฉ๋ฒ• URL/docs ๋ฅผ ์ถ”๊ฐ€ํ•˜๋ฉด ์ ‘๊ทผ ๊ฐ€๋Šฅ

728x90
๋ฐ˜์‘ํ˜•

'๊ฐœ๋ฐœ > Python' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

FastAPI - Redis ์—ฐ๋™  (0) 2023.07.31
FastAPI - DB ์—ฐ๋™  (0) 2023.07.31
Python - Uvicorn  (0) 2023.07.31
Python - FastAPI  (0) 2023.07.31
Python Framework  (0) 2023.07.31