본문 바로가기

Plo Hanghae99/Plo Ready for hanghae99

Ready For Hanhae -4주차-


항해 D-83

Ready For Hanghae


-3주차 개발일지-

Flask , (Ajax)Get , (Ajax)Post

[Flask] 파이썬으로 작성된 웹 프레임워크
[Flask]폴더세팅 static, templates + (index.html)  + app.py
[Get] CRUD 中 Read : 통상적으로 데이터를 요청함 URL 뒤에 물음표를 붙여 key=value?로 전달 google.com?q=북극곰
[Post ] CRUD 中 Create , Update , Delete : 바로 보이지 않는 HTML body에 key:value 형태로 전달
ex (회원가입, 회원탈퇴, 비밀번호 수정)

 


- Mini Project [ 1 ] -

[나만의 메모장 완성하기]

 

-Server-

from flask import Flask, render_template, jsonify, request
app = Flask(__name__)

import requests
from bs4 import BeautifulSoup

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta

## HTML을 주는 부분
@app.route('/')
def home():
   return render_template('index.html')

@app.route('/memo', methods=['GET'])
def listing():
    articles = list(db.articles.find({},{'_id':False}))

    return jsonify({'all_articles':articles})

## API 역할을 하는 부분
@app.route('/memo', methods=['POST'])
def saving():
    url_receive = request.form['url_give']
    comment_receive = request.form['comment_give']

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
    data = requests.get(url_receive, headers=headers)

    soup = BeautifulSoup(data.text, 'html.parser')

    # 여기에 코딩을 해서 meta tag를 먼저 가져와보겠습니다.

    title = soup.select_one('meta[property="og:title"]')['content']
    image = soup.select_one('meta[property="og:image"]')['content']
    desc = soup.select_one('meta[property="og:description"]')['content']

    doc = {
        'title' : title ,
        'image' : image ,
        'desc'  : desc  ,
        'url'   : url_receive ,
        'comment' : comment_receive
    }

    db.articles.insert_one(doc)

    return jsonify({'msg':'저장이 완료되었습니다!'})

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

-Client-

function postArticle() {
                let url =$('#post-url').val()
                let comment =$('#post-comment').val()
                $.ajax({
                    type: "POST",
                    url: "/memo",
                    data: {url_give : url , comment_give : comment},
                    success: function (response) { // 성공하면
                        alert(response["msg"]);
                        window.location.reload()
                    }
                })
            }

            function showArticles() {
                $.ajax({
                    type: "GET",
                    url: "/memo?sample_give=샘플데이터",
                    data: {},
                    success: function (response) {
                        let articles = response['all_articles'];
                        for (let i = 0 ; i < articles.length ; i++){
                            let title = articles[i]['title']
                            let image = articles[i]['image']
                            let desc = articles[i]['desc']
                            let url = articles[i]['url']
                            let comment = articles[i]['comment']

                            temp_html = ` <div class="card">
                                            <img class="card-img-top"
                                                 src="${image}"
                                                 alt="Card image cap">
                                            <div class="card-body">
                                                <a target="_blank" href="${url}" class="card-title">${title}</a>
                                                <p class="card-text">${desc}</p>
                                                <p class="card-text comment">${comment}</p>
                                            </div>
                                          </div>`
                            $('#cards-box').append(temp_html)

 

이해하는데에 굉장히 어려웠다.. 프로젝트를 숙제 제외 총 세개를 비슷한 내용으로 진행했고

이번주차 튜터님과 함깨한 마지막 프로젝트였으며 이전에 두개의 프로젝트를 진행했음에도 이해가 잘 되지않아 많은 어려움을 겪었다.

서버에서 flask를 , 클라이언트에서 ajax를 코딩해 나갈 때

서버에서 POST를 코딩하고 클라이언트에서 GET에 코딩을하는 실수도 있었고

POST와 GET의 개념이 제대로 잡히지 않아 어디에 코딩을 시작해야할지 튜터님을 따라가면서도 많이 헤맸던 것 같다.


 - Mini Project [ 2 ] -

[나만의 쇼핑몰 완성하기]

 

-Server-

from flask import Flask, render_template, jsonify, request
from bs4 import BeautifulSoup
import requests

app = Flask(__name__)

from pymongo import MongoClient

client = MongoClient('localhost', 27017)
db = client.dbhomework

## HTML 화면 보여주기
@app.route('/')
def homework():
    return render_template('index.html')


# 주문하기(POST) API
@app.route('/order', methods=['POST'])
def save_order():
    name_receive = request.form['name_give']
    amount_receive = request.form['amount_give']
    address_receive = request.form['address_give']
    phone_receive = request.form['phone_give']

    doc = {
        'name': name_receive,
        'amount': amount_receive,
        'address': address_receive,
        'phone': phone_receive,
    }

    db.shop.insert_one(doc)

    return jsonify({'msg': '주문정보 저장이 완료되었습니다.'})



# 주문 목록보기(Read) API
@app.route('/order', methods=['GET'])
def view_orders():
    orderer = list(db.shop.find({}, {'_id': False}))
    return jsonify({'save' : orderer})




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

 

-Client-

 

        function order_listing() {
            // 주문목록 보기 API 연결
            $.ajax({
                type: "GET",
                url: "/order",
                data: {},
                success: function (response) {

                    let orderer = response['save']

                    for (let i = 0; i < orderer.length; i++) {
                        let name_get = orderer[i]['name']
                        let amount_get = orderer[i]['amount']
                        let address_get = orderer[i]['address']
                        let phone_get = orderer[i]['phone']

                        let temp_html = `<tr>
                                                <th scope="col">${name_get}</th>
                                                <th scope="col">${amount_get}</th>
                                                <th scope="col">${address_get}</th>
                                                <th scope="col">${phone_get}</th>
                                         </tr>`

                        $('#orderer').append(temp_html)
                    }
                }
            })
        }

        function order() {
            let name = $('#name').val()
            let amount = $('#amount').val()
            let address = $('#address').val()
            let phone = $('#phone').val()

            // 주문하기 API 연결
            $.ajax({
                type: "POST",
                url: "/order",
                data: {name_give: name, amount_give: amount, address_give: address, phone_give: phone},
                success: function (response) { // 성공하면
                    alert(response["msg"])
                    window.location.reload();
                }
            })
        }

 

이전에 세개의 프로젝트를 했음에도 불구하고 4주차의 내용을 제대로 이해하지 못해 , 도저히 혼자서 숙제를 해나갈 수 없을 것 같았다.

4주차 강의를 한번 더 듣고 수업을 진행할까 했으나 강의자료를보고 한번 되짚어본 후 결정하기로하고

강의자료를 참고하려 들어갔고 강의자료 내용 중 [GET = Read , POST = Create , Update , Delete] 이라

설명되어있는 부분을보고 이전에 알고있던 CRUD의 개념과 동일 내용임을 인지했고 확실하게 이해했다.

허나 이해와는 다르게 코드를 써내려가기에는 무리가있었고 이전에 진행했던 프로젝트의 코드들을 참고하여

3일이라는 시간이 걸렸지만 이번에도 해설영상을 보지않고 생각처럼 구현되지 않을 때 마다 문제점을 찾고

해결해나가며 스스로 헤쳐나갔음에 뿌듯함을 느낀다.

처음썼던 POST코드가 제대로 작동하지 않아 서버와 클라이언트 모두 POST 코드블럭들을 날려버리고

다시 처음부터 작성 후 실행 후 robo3T를 실행했을 때 제대로 저장된 데이터를 봤을 때 느꼈던 짜릿함을

오래오래 기억해둬야겠다.


-Review-

 

4주차는 강의내용 외에도 여러가지 문제가 많아 약간의 스트레스가 있었다.

맥OS를 Monterey로 업데이트하고 난 후 기존 맥북에 파이썬이 하나 더 업데이트되었고

port:5000을 사용하는 맥 기본 프로그램도 업데이트됐다. 

4주차 강의를 진행할 때 서버에서

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

작성된코드 스니펫을 사용했고 맥OS 업데이트 후 숙제를 진행하려 서버를 run했으나 

OSError : [Errno  48] Address alredy in use 라는

낯선 에러코드를 마주했다.. 구글링을 해보니 pytho이 두개이상 메모리에서 실행되고 있을 때

발생하는 에러로 finder , 시스템 리포트 , 터미널을 이용하여 해결하는 해결책을 제시해 주셨는데

구글링으로 나오는 모든 방법을 동원해도 해결되지 않았고

결국 일요일 늦은 10시 항해99 튜터님께 도움을 청했다.

튜터님은 늦은 시간임에도 불구하고 질문 후 5분만에 답변을 주셨고

port:5000을 사용하는 기본 프로그램이 업데이트된 것 같으니 port:8000으로 바꾸는 방법으로 해결해주셨다.

답변을 해주시면서도 port번호를 바꾸는 해결방안을 제시해주시며 바꾸는 방법은 수강생 스스로 찾아갈 수 있게끔

방향을 잡아주시는 튜터님의 방식에서 질문에서 답을 찾기보단

스스로 생각하는 능력을 키우는데에 많은 도움을 받고있다는 생각이 들었다.

 

'Plo Hanghae99 > Plo Ready for hanghae99' 카테고리의 다른 글

Ready For Hanhae -3주차-  (0) 2021.12.09
Ready For Hanhae -2주차-  (0) 2021.12.04
Ready For Hanhae -1주차-  (0) 2021.11.27