Develop/FastAPI

FastAPI 프로젝트 진행(HTML 렌더링, DB 연결)- 84

김잠봉 2023. 1. 29. 15:27
728x90

 

PostgreSQL user 테이블
PostgreSQL Todos 테이블

 

 

1. todos.py 수정

#라이브러리 추가
from sqlalchemy.orm import Session
from fastapi import Depends


#API 수정
@router.get("/", response_class=HTMLResponse)
async def read_all_by_user(request: Request, db: Session = Depends(get_db)):
	#Todos 테이블 데이터 전체 호출
    todos = db.query(models.Todos).filter(models.Todos.owner_id == 6).all()
    
    #Todos 테이블 데이터 렌더링
    return templates.TemplateResponse("home.html", {"request":request, "todos":todos})

 

2. home.html 수정

{% include 'layout.html' %}

<!--todo list 만들기-->
<div class="container">
    <div class="card text-center">
        <!--상단제목-->
        <div class="card-header">
        	Your Todos!
        </div>
        <!--하단제목-->
        <div class="card-body">
        	<h5 class="card-title">List of your Todos!</h5>
            <p class="card-text">Information regarding stuff that needs to be complete</p>

            <!--테이블 만들기-->
            <table class="table table-hover">
                <thead>
                    <tr>
                    <!--해당 셀이 column(열)-->
                    <th scope="col">Actions</th>
                    <th scope="col">Info</th>
                    <th scope="col">#</th>
                    </tr>
                </thead>

                <tbody>
                    {% for todo in todos %}
                    <!--1번 section-->
                    <tr class="pointer">
                    <td>1</td>
                    <td>{{todo.title}}</td>
                    <td>
                    <button 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>
                {% endfor %}

                </tbody>
            </table>

        	<a href="#" class="btn btn-primary">Add a new Todo!</a>

        </div>
    </div>
</div>
{% for a in data %} - Jinja의 python의 for문과 동일한 역할
{{xx. xx}} - print문과 동일한 역할
{% endfor %} - for문이 종료되는 지점
onclick= "" - 클릭을 했을 때 설정한 주소로 연결된다.  

todos의 데이터가 for문을 돌려서 title을 화면에 뿌려준다.

위 사진의 edit를 누르면 연결되는 페이지 edit.html이 잘 호출되고 있다.

 

 

※ 현재 Actions가 하드 코딩 되어있음으로 테이블의 index 값을 바꿔준다.

<tbody>
    {% for todo in todos %}
    <!--1번 section-->
    <tr class="pointer">
    	<td>{{loop.index}}</td>
    	<td>{{todo.title}}</td>
    	<td>
            <button 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>
	{% endfor %}

</tbody>
<td> 1 </td> >> <td> {{loop.index}} </td> 변경

728x90
SMALL