Blog

[Flask] Flask framework 미니프로젝트(project fan) 04 (Frontend 기초 테스트 View 페이지 작성 및 모듈화 + 현재날짜 HTML에 표기 구현)

Author
Summary
Frontend 기초 테스트 View 페이지 작성 및 모듈화 + 현재날짜 HTML에 표기 구현
Category
Study
Tags
Python&Flask
Favorite
Memory Date
2023/07/17
Progress Status
Done
Cross Reference Study
Related Media
Related Thought
Related Lessons
tag
날짜
작성자
진행상황
진행 전
태그구분
5 more properties
새로운 앨범 너무 멋져요!개발하고자 하는 프로젝트의 View 페이지(HTML,CSS)와 JavaScript 연결 테스트용 작성
CSS, JavaScript 모듈화(Static) 및 참조 링크 설정

1. HTML

경로 : (project_root)fan/templates/index.html
Body는 Container(Wrap)내 Header / Content / Footer 로 구분
Header :
웹 페이지 타이틀
현재 기온을 나타내주는 부분 #temp
현재 날짜 #date
가수의 노래 오늘 순위 #rank
해당 노래의 순위 변동 #rankdiff
Content :
(Input form)
응원 댓글을 기록하는 양식은 다음과 같다.
닉네임 (#name)을 input 태그를 통해 value 획득
응원 댓글 (#comment)를 textarea 태그를 통해 value 획득
댓글 남기기 버튼은 onclick save_comment() 함수를 호출
(Output List)
div(#comment-list)에 1열로 구성
각 행마다 div(#card>div(#card-body)>blockquote로 1개의 카드 형태가 1행씩 붙음
blockquote 클래스 부트스트랩 테마가 적용됨
blockquote 카드의 내용은 아래처럼 2개의 div로 구성
상단 p : 응원 댓글 내용(ex: 새로운 앨범 너무 멋져요!)
하단 footer(.blockquote footer) : 닉네임(ex: - 호빵맨)
Footer : None
div(#comment-list)>div(.card) 에 추후 guestbook_post() 함수의 결과가 1행씩 추가 될 예정
<!-- HTML Doctype선언문 --><!DOCTYPE html> <html lang="en"> <head> <!-- 인코딩 캐릭터셋 UTF-8지정 --><meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- 부트스트랩 css 참조 --><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" /> <!-- jquery 참조 --><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- 부트스트랩 javascript 참조 --><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <!-- Google Font 참조 --><link href="https://fonts.googleapis.com/css2?family=Gothic+A1&family=Nanum+Gothic+Coding&family=Noto+Sans+KR&family=Noto+Serif+KR&family=Orbit&display=swap" rel="stylesheet"> <!-- JS 모듈화 참조 --><!-- Flask용 --><!-- <script src="{{ url_for('static', filename='js/script.js') }}"></script> --><!-- Live Server 용 --><script src="/static/js/script.js"></script> <!-- CSS 모듈화 참조 --><!-- Flask용 --><!-- <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}"> --><!-- Live Server 용 --><link rel="stylesheet" href="/static/css/style.css" /> <title>초미니홈피 - 팬명록</title> </head> <body> <!-- Container(Wrap) --><div id="wrap"> <!-- Header --><div id="header" class="mypic"> <h1>NEW JEANS 팬명록</h1> <p>현재기온: <span id="temp">36</span></p> <div id="ranking"> <p>날짜 : <span id="date"></span></p> <p>"ABC"의 "노래제목" Spotify 오늘 순위 : <span id="rank">99</span></p> <p>순위 변동(전일대비) : <span id="rankdiff">+1</span></p> </div> </div> <!-- Content --><div id="content"> <!-- (Input Form) --><div class="mypost"> <div class="form-floating mb-3"> <input type="text" class="form-control" id="name" placeholder="url" /> <label for="floatingInput">닉네임</label> </div> <div class="form-floating"> <textarea class="form-control" placeholder="Leave a comment here" id="comment" style="height: 100px"></textarea> <label for="floatingTextarea2">응원댓글</label> </div> <button onclick="save_comment()" type="button" class="btn btn-dark"> 댓글 남기기 </button> </div><!-- End Input Form--><!-- (Output List) --><div class="mycards" id="comment-list"> <div class="card"> <div class="card-body"> <blockquote class="blockquote mb-0"> <p>새로운 앨범 너무 멋져요!</p> <footer class="blockquote-footer">호빵맨</footer> </blockquote> </div> </div> <div class="card"> <div class="card-body"> <blockquote class="blockquote mb-0"> <p>새로운 앨범 너무 멋져요!</p> <footer class="blockquote-footer">호빵맨</footer> </blockquote> </div> </div> <div class="card"> <div class="card-body"> <blockquote class="blockquote mb-0"> <p>새로운 앨범 너무 멋져요!</p> <footer class="blockquote-footer">호빵맨</footer> </blockquote> </div> </div> </div><!-- End Output list--></div><!-- End Content--><!-- Footer --><!-- <div id="footer"> None </div> --></div><!-- End Wrap--></body> </html>
HTML
복사

2. CSS

(project_root)fan/static/css/style.css로 분리 모듈화
Google Fonts "Orbit" 글씨체 전체 적용
Image 배경 어둡게 적용
(Input form) 입력 양식 박스인 div(.mypost) 그림자 효과 box-shadow 적용, 너비 500px 고정
button 투명화 transparent 적용
(Output list) 응원 댓글 리스트 div(.mycards) 너비 500px 고정
각 응원 댓글 div(.mycards)>div(.card) 마다 위 아래 여백 10px로 붙지 않도록 설정
기타 요소별 디자인은 index.html에 참조된 Bootstrap 테마 사용
* { font-family: 'Orbit', sans-serif; } .mypic { width: 100%; height: 300px; background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("https://koreajoongangdaily.joins.com/data/photo/2022/08/15/0749e0ee-0def-49d2-8f4e-e3e0d0ee008d.jpg"); background-position: center 30%; background-size: cover; color: white; display: flex; flex-direction: column; align-items: center; justify-content: center; } .mypost { width: 95%; max-width: 500px; margin: 20px auto 20px auto; box-shadow: 0px 0px 3px 0px black; padding: 20px; } .mypost>button { margin-top: 15px; } .mycards { width: 95%; max-width: 500px; margin: auto; } .mycards>.card { margin-top: 10px; margin-bottom: 10px; }
CSS
복사

3. JavaScript

(project_root)fan/static/js/script.js로 분리 모듈화
set_temp(), show_comment(), show_ranking(), show_date();함수는 $(document).ready()를 통해 View 페이지가 생성 될 때 바로 실행된다.
set_temp() : OpenAPI 서울시 날씨 정보를 받아와 보여줄 예정
show_comment() : DB로부터 응원 댓글을 불러오는 GET 요청 예정
show_ranking() : 지정된 Spotify 랭킹 차트에서 Super Shy 노래의 순위를 크롤링한 정보를 보여줄 예정
show_date() : date()를 통해 현재 날짜를 보여 줄 예정
localhost:5001/guestbook URL로 GET 요청을 보낸다.
(->백엔드가 수신-> /guestbook URL의 GET 요청을 응답하는 메서드가 실행되고 결과가 반환된다.)
반환 받은 데이터를 json으로 변환시켜 알림창에 보여준다.
날짜표기는 date()함수를 이용
시간 객체를 생성하고, date.getFullYear, .getMonth, .getDate, .getDay, .getHour, ...등으로 시간을 불러 올 수 있다.
주의할점
월은 0,1,2,3,4,5,6,7,8,9,10,11로 나타나므로 +1을 해서 총 12개월을 만들면 된다.
요일은 0,1,2,3,4,5,6 값으로 나타나므로 월,화,수,목,금,토,일을 리스트화 시키고 index번호와 매칭시켜 불러올 수 있다.
document.getElementById를 통해 HTML의 ID를 선택 할 수 있다.
위 선택한 객체에 .innerText로 원하는 텍스트를 입력 할 수 있다.
// [Read] $(document).ready(function () { set_temp(); show_comment(); show_ranking(); show_date(); }); // [Create]function save_comment() { let formData = new FormData(); formData.append("sample_give", "샘플데이터"); fetch('/guestbook', { method: "POST", body: formData }).then((res) => res.json()).then((data) => { //console.log(data) alert(data["msg"]); }); } function set_temp() { fetch("http://spartacodingclub.shop/sparta_api/weather/seoul").then((res) => res.json()).then((data) => { console.log(data) }); } function show_comment() { fetch('/guestbook').then((res) => res.json()).then((data) => { alert(data["msg"]) }) } function show_ranking() { fetch('/ranking').then((res) => res.json()).then((data) => { alert(data["msg"]) }) } // [Date]function show_date() { let Target = document.getElementById("date"); let time = new Date(); let year = time.getFullYear(); let month = time.getMonth(); let date = time.getDate(); let day = time.getDay(); let week = ['일', '월', '화', '수', '목', '금', '토']; // let hours = time.getHours();// let minutes = time.getMinutes();// let seconds = time.getSeconds(); Target.innerText = `${year}${month + 1}${date}${week[day]}요일 `; // `${hours < 10 ? `0${hours}` : hours}:${minutes < 10 ? `0${minutes}` : minutes}:${seconds < 10 ? `0${seconds}` : seconds}`; }
JavaScript
복사
View 페이지 화면 상태(테스트용 하드 코딩 상태)