_won_
wonprogrammer
_won_
전체 방문자
오늘
어제
  • 분류 전체보기
    • woncoding
      • TIL
      • WIL
    • source Code
      • Python
      • Programmers
      • BAEKJOON

블로그 메뉴

  • 방명록

티스토리

Github · Wonprogrammer
hELLO · Designed By 정상우.
_won_

wonprogrammer

woncoding/TIL

TIL | 8.31.수 [1_mini_project]

2022. 8. 31. 23:29

- 1_mini_project : html / css + pymongo / Flask 완성

 

 

[1,2페이지 방명록 작성 서버에 Data 전송 + 업데이트 된 데이터 3페이지에 업로드]

 

POST 요청 확인 Ajax코드

[1, 2page] : 방명록 작성해서 db에 POST

function save_comment() {
    let name = $('#name').val()
    let comment = $('#comment').val()

    $.ajax({
        type: "POST",
        url: "/1_mini_project",
        data: {name_give: name, comment_give: comment},
        success: function (response) {
            alert(response["msg"])
            window.location.reload()
        }
    })
}

 

 

GET 요청 확인 Ajax코드

[3page] : 작성된 방명록 db에서 GET해서 페이지에 나타내기

$(document).ready(function () {
    show_comment();
});

function show_comment() {
    $.ajax({
        type: "GET",
        url: "/1_mini_project",
        data: {},
        success: function (response) {
            let rows = response['comments']

            for (let i = 0; i < rows.length; i++) {
                let name = rows[i]['name']
                let comment = rows[i]['comment']

                let temp_html = `<tr>
                                    <td>${name}</td>
                                    <td>${comment}</td>
                                </tr>`

                $('#comment-list').append(temp_html)
            }
        }
    });
}

 

 

 

POST 요청 API코드 / GET 요청 API코드

[app.py]

// 필수 패키지 및 선언
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

from pymongo import MongoClient

import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://won:sparta@cluster0.4vhehoz.mongodb.net/?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.miniproject


// 서버 오픈시 실행되는 메인 html = '1_page.html'
@app.route('/')
def home():
   return render_template('1_page.html')



// 1_mini_project html 파일 중 POST 요청 된 데이터 db에 저장
@app.route('/1_mini_project', methods=['POST'])
def comment_post():
    name_receive = request.form['name_give']
    comment_receive = request.form['comment_give']

    doc = {
       'name': name_receive,
       'comment': comment_receive
    }
    db.visitor.insert_one(doc)
    return jsonify({'msg': '저장 완료!'})



// 메인 페이지에서 2페이지로 넘어가는 루트를 만들어주기 (팀원별로 아래 코드 4개 만들어 준다)
@app.route('/2_page_lhw')
def page_1():
    return render_template('2_page_lhw.html')



// 2페이지에서 3페이지로 넘어가는 루트를 만들어주기
@app.route('/3_page.html')
def cpage():
   return render_template('3_page.html')



// 1_mini_project html 파일 중 GET 요청 된 데이터 comment_list에 불러오기 (: frontend)
@app.route('/1_mini_project', methods=['GET'])
def comment_get():
    comment_list = list(db.visitor.find({}, {'_id': False}))
    return jsonify({'comments': comment_list})



if __name__ == '__main__':
   app.run('0.0.0.0',port=5000,debug=True)

 

 

'woncoding > TIL' 카테고리의 다른 글

TIL | 9.5.월 [Python 언어의 이해 / Python 기초]  (1) 2022.09.05
TIL | 9.2.금 [튜플 / 집합 / f-string / 예외처리 / 파일분리 / map, lambda, filter / class]  (0) 2022.09.02
TIL | 9.1.목 [변수 / 리스트 / 딕셔너리 / 조건,반복문 / 함수]  (0) 2022.09.01
TIL | 8.30.화 [pymongo / Flask]  (0) 2022.08.30
TIL | 8.29.월 [Html / CSS / Javascript]  (0) 2022.08.29
    'woncoding/TIL' 카테고리의 다른 글
    • TIL | 9.2.금 [튜플 / 집합 / f-string / 예외처리 / 파일분리 / map, lambda, filter / class]
    • TIL | 9.1.목 [변수 / 리스트 / 딕셔너리 / 조건,반복문 / 함수]
    • TIL | 8.30.화 [pymongo / Flask]
    • TIL | 8.29.월 [Html / CSS / Javascript]
    _won_
    _won_
    Coding Practice blog

    티스토리툴바