반응형
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>
반응형
'Programming > Python_Web' 카테고리의 다른 글
FastAPI - Jinja2, Form, Redirect 적용 (0) | 2021.09.11 |
---|---|
FastAPI - MySQL CRUD (0) | 2021.09.10 |
FastAPI - Jinja2로 프론트 적용하기 (0) | 2021.09.09 |
Flask강좌6 - 등록/로그인/로그아웃 (0) | 2020.12.04 |
Flask강좌5 - Flask form입력 (0) | 2020.12.03 |