-
항해 99 5기 TIL_1항해 99 2022. 1. 11. 02:00
▶ Today I Learned
간단한 OT 후 미니 프로젝트 진행 1일차,
프로젝트 사이트 중 '메인페이지' 담당
<프로젝트 구현해야할 기능>
로고 클릭 시 메인 홈으로 이동
:
<a href="/"><img src="메인 로고" alt="프로젝트명">홈으로 이동 로고</a>
로그인한 사용자 표시
:미구현
로그인/로그아웃 표시 버튼(로그인 상태면 로그아웃으로 표시되며 로그아웃 후 메인페이지로 이동, 아니라면 로그인으로 표시되며 로그인 페이지로 이동)
:미구현
검색창 및 버튼 (입력 후 일치하는 결과가 있다면 게시글 사이트로 이동, 검색어와 일치하는 단어가 있는 제목의 게시글 모두 표시)
: 검색버튼 클릭 시 함수 발동
<button id="search_btn" type="submit" title="검색" class="search_submit" onclick=findingResult()> </button>
함수 findingResult()
function findingResult () { if (로그인 했을 시) { location.href = "게시글 페이지" $('#searching_word').text // match()같은 함수를 이용해 위 텍스트와 게시글 제목이 겹치는 부분이 있을 경우 // 해당되는 게시글 모두 출력 } else { alert('로그인 후 이용해주시기 바랍니다.') // 로그인 페이지로 리디렉션 location.href = "로그인 페이지" } }
사이트 대표이미지 삽입
:
<img src="이미지 소스" alt="My Image">
기존 작성된 글 목록 하단에 표시 (전체 표시하지 않고 그라데이션으로 가려서 일부 표시)
: HTML 측 코드
div class='showArticles'> <!-- 글 목록 넣는 부분 --> {{ articles }} </div>
서버(파이썬) 측 코드
@app.route('/') def showArticles(): articles = requests.get('게시글 있는 URL'[사이트 내 게시글 부분 div같은 태그명 또는 bs4로 긁어오기, 그중 상위 몇개만]) 모두 다 들고오면 로딩 시 페이지 느릴 수 있음 return render_template('index.html', articles = articles)
<파이썬>
- 함수 선언 시 'def 함수명(인자)' 구조
- 서버사이드 파일app.py와 클라이언트 사이드 파일 index.html을 이어주기 위해선 app.py에서 render_template을 해줘야함
- render_template은 flask의 함수이며 jinja2를 기반으로 작동함, templates에 있는 html을 불러올 때 사용
- jsonify는 flask의 함수이며 값을 JSON (키:값)형태로 Response라는 파라미터에 넘김
- __name__: 현재 보고있는 모듈
- 현재 보고있는 해당 모듈이 주 모듈이라는 소리
if __name__ == '__main__':
<파이썬_Jinja2>
Jinja2 - 파이썬 템플릿 언어 (템플릿 엔진이라고도 하는 듯 하다.), 쉽게 말해 기존의 document에 새로운 데이터를 더하여 새로운 document를 만들어 내도록 도와주는 엔진이다.
즉, 기존의 HTML에 서버쪽의 데이터를 집어넣어 새로운 HTML을 구성하게 해준다.
SSR을 하는 것이다.
-사용형태-
{{파이썬 파일 내에서의 변수}}
{%파이썬 소스코드, 파이썬 코드를 html에서 사용할 수 있게 해준다%}
cf) 파이썬에서 코드를 작성할 때와 다른 부분이 있긴 하다. 예컨대 반복문을 쓸 때는 반복문이 끝나는 구간에 {% endfor %} 라는 구문을, if문에선 끝나는 구간에 {% endif %} 추가해준다.
파이썬 내에선 indented(tab키를 눌러 띄우는 것)로 구분이 가능했지만
html내에선 indented가 다른 의미를 가지기 때문에 저런 구문을 추가해주어야 한다.
ex)
{% set a = rows[0]['PeopleName'] %} <p>Name: {{a}}</p>
html코드 상에서 a에 저렇게 {{}}를 씌우는 이유는 변수 선언을 파이썬에서 했기 때문!
({%%} 안에서 작성한 코드는 파이썬에서 작성한 것이나 다름없다!)
어떤 장점이 있을까?
1) Jinja2를 이용하므로써 html내에서 코드를 복잡하게 쓸 필요가 없어졌다.
2) 정적인 HTML안에서 동적인 기능을 구현할 수 있다.
여기서 CSR을 써서 구현하는 것과 Jinja2라는 SSR을 사용해 구현하는 것 모두 같은 결과를 낼 수도 있다.
전자와 후자 같은 결과라는 가정하에 예시를 들면
전자는
$(document).ready(function () { get_list() }) function get_list() { $.ajax({ type: "GET", url: "API주소", data: {}, success: function (response) { let rows = response["peopleInfo"]["height"]; console.log(rows) } }) }
후자는
{% set a = rows[0]['peopleInfo']['height'] %} console.log({{a}})
위에 적힌 것 말고도 장점이 더 있을까?
단점은 무엇일까?
1) 파이썬 파일 내에서 get을 해야하므로 코드가 길어진다.
또 무엇이 있을까?
<자바스크립트>
window.location.href는 현재 페이지를 지정하는 특정페이지로 돌릴 때 사용 가능한 Javascript 오브젝트이다.
window.location.href = "이동 원하는 링크"
CSR(Client Side Rendering): 클라이언트 파일(HTML)안에서 자바스크립트를 활용해 자체적으로 데이터를 넘겨줄 때,
서버에 데이터를 넘기지 않고 브라우저에서 자체적으로 상호작용해 HTML을 완성하는 방법
SSR(Server Side Rendering): 서버에서 HTML의 데이터를 모두 채워넣어 클라이언트로 보내주는 방식, 즉, 서버 측에서 HTML을 모두 그려서 브라우저로 넘겨주는 방식
▶ 느낀 점
하고 싶었던 개발자가 되기 위해 신청했던 부트캠프. 드디어 시작이다!
호기심이 많고 스스로 문제를 파고들어갈 줄 아는 사람, 함께 밥먹고 싶고 일하고 싶은 사람이 되기위해 부단히 노력했다.
그러나 하루종일 찾고 찾아도 원하는 기능을 구현하기란 쉽지 않았다.
간단해 보이는 프로젝트여도 기능 하나를 구현하는 데 고려해야할 것들이 산더미였다.
이래서 개발자는 힘들다고들 하나보다.. 하지만 절대 포기하지 않을 것이다.
내일도 화이팅! -새벽 2시까지 작업을 하고 블로그를 정리하며-
▶ 공부 시 참고 링크들
부트스트랩 4 버전
https://www.codingfactory.net/10364
Flask를 시작하기 위해
https://medium.com/@mystar09070907/flask-%EC%8B%9C%EC%9E%91%ED%95%98%EA%B8%B0-1738c4b6e465
플라스크 공식 문서
https://flask.palletsprojects.com/en/2.0.x/api/?highlight=render_template#flask.render_template
서버사이드 렌더링
'항해 99' 카테고리의 다른 글
항해 99 5기 TIL_3 (0) 2022.01.13 항해 99 5기 TIL_2 (0) 2022.01.12 항해 99 - 웹개발 종합반 - WIL - 5 (0) 2022.01.05 항해 99 - 웹개발 종합반 - WIL - 4 (0) 2022.01.05 항해 99 - 웹개발 종합반 - WIL - 3 (0) 2022.01.04