Develop/FastAPI
FastAPI 프로젝트 진행(완료 버튼 작동, RedirectResponse) - 89
김잠봉
2023. 1. 29. 17:20
728x90
1. 새로운 API 생성
@router.get("/complete/{todo_id}", response_class=HTMLResponse)
async def complete_todo(request: Request, todo_id: int, db: Session = Depends(get_db)):
todo = db.query(models.Todos).filter(models.Todos.id == todo_id).first()
todo.complete = not todo.complete
db.add(todo)
db.flush()
db.commit()
return RedirectResponse(url="/todos", status_code=status.HTTP_302_FOUND)
RedirectResponse - complete_todo 호출 이후 todos로 이동
not todo.complete - complete의 type은 boolean으로 False값이 오면 True로 True값이 오면 False로 바꾼다.
2. home.html 수정
<tbody>
{% for todo in todos %}
{% if todo.complete == False %}
<tr class="pointer">
<td>{{loop.index}}</td>
<td>{{todo.title}}</td>
<td>
<button onclick="window.location.href='complete/{{todo.id}}'"
type="button" class="btn btn-success">Complete</button>
<button onclick="window.location.href='edit-todo/{{todo.id}}'"
type="button" class="btn btn-info">Edit
</button>
</td>
</tr>
{% else %}
<tr class="pointer alert alert-success">
<td>{{loop.index}}</td>
<td class="strike-through-td">{{todo.title}}</td>
<td>
<button onclick="window.location.href='complete/{{todo.id}}'"
type="button" class="btn btn-success">Undo</button>
<button onclick="window.location.href='edit-todo/{{todo.id}}'"
type="button" class="btn btn-info">Edit
</button>
</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
{% for xx in xx%} - python for문
{% if %} - python if문
{% else %} - python else문
Complete 버튼을 누르면 False값이 True로 업데이트 되면서 else 구문으로 넘어간다.
Undo 버튼을 누르면 True값이 False로 업데이트 되면서 if 구문으로 넘어간다.
else구문의 td class는 static의 base.css에 값이 설정되어 있다. - 글자에 라인선이 그어짐
else구문의 tr class는 static의 bootstrap.css에 값이 설정되어있다. - 상자 전체에 초록색이 채워짐.
3. 웹 확인
728x90
SMALL