본문 바로가기

Programming/Python_Web

FastAPI 시작하기

반응형

1. 폴더구조

2. 라이브러리 설치

 

pip install fastapi uvicorn pydantic jinja2

<main.py>

import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel

import requests

app = FastAPI()
db=[]
#----------------------------------------------------------------------------------------------------------
# data models

class City(BaseModel):
    name: str
    timezone: str

templates = Jinja2Templates(directory="templates")

#app.include_router(index.router);

@app.get("/")
async def root():
    return {"message": "Hello World"}

@app.get("/cities", response_class=HTMLResponse)
def get_cities(request: Request):
    context = {}
    rsCity = []

    cnt = 0
    for city in db:
        str=f"http://worldtimeapi.org/api/timezone/{city['timezone']}"
        print(str)
        r = requests.get(str)
        cur_time = r.json()['datetime']

        cnt += 1
        rsCity.append({'id': cnt, 'name':city['name'], 'timezone': city['timezone'], 'current_time': cur_time})

    context['request'] = request
    context['rsCity'] = rsCity

    return templates.TemplateResponse('city_list.html', context)

@app.get('/cities/{city_id}')
def get_city(city_id: int):
    city = db[city_id-1]
    r = requests.get(f"http://worldtimezpi.org/api/timezone/{city['timezone']}")
    cur_time = r.json()['datetime']
    return {'name': city['name'], 'timezone': city['timezone'], 'current_time': cur_time}

@app.post('/cities')
def create_city(city: City):
    db.append(city.dict())
    return db[-1]

@app.delete('/cities/{city_id}')
def delete_city(city_id: int):
    db.pop(city_id-1)
    return {}


if __name__ == '__main__':
    uvicorn.run(app)

 

<templates/city_list.py>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>City list</h1>
    {% if rsCity %}
        {% for city in rsCity %}
            <div>
                {{city.name}} - {{city.timezone}}
            </div>
        {% endfor %}
    {% else %}
            <div>
                No city...
            </div>
    {% endif %}
</body>
</html>
반응형