mongoDB 그리고 GET,POST

쭈오기단·2023년 2월 1일

항해

목록 보기
6/9

데이터

  • 데이터는 왜 사용하는가?
  1. 잘 보관하기 위해서
  2. 나중에 잘 찾기 위해서
    눈에 보이지 않지만 index라는 순서로 데이터들이 정렬되어 있다.
  • 데이터베이스는 크게 두가지 종류가 있다.
  1. SQL : 행/열의 생김세가 정해진 엑셀에 데이터를 저장하는 것과 유사함. 정형화 되어 있는것 만큼 갑자기 중간에 열을 하나 더하거나 빼는 것이 어렵다. 데이터의 일관성이나 분석에 용이할 수 있다.
  2. No-SQL : 딕셔너리 형태로 데이터를 저장해두는 DB. 데이터 하나마다 같은 값들을 가질 필요가 없다.(정형화된 형식이 반드시 필요하지 않음) 자유로운 형태의 데이터 적재에 유리한 대신 일관성이 부족하다.

최근 데이터베이스는 프로그램같은 것이다. 하지만 이마저도 요즘은 클라우드 형태로 제공한다.

mongoDB사용하기

라이브러리 설치가 필요하다.

pymongo, dnspython 패키지를 설치하자.

지니에서 크롤링하기

import requests
from bs4 import BeautifulSoup

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('https://www.genie.co.kr/chart/top200?ditc=M&rtm=N&ymd=20210701',headers=headers)

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

trs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')

for tr in trs:
    title = tr.select_one('td.info > a.title.ellipsis').text.strip()
    rank = tr.select_one('td.number').text[0:2].strip()
    artist = tr.select_one('td.info > a.artist.ellipsis').text
    print(rank, title, artist)

for문을 사용하는 것에 좀 더 익숙해질 필요가 있는것 같다.
자료를 타고 타고 들어가는 것에 주의해서 공부해보자,

Flask

파이썬 기반의 웹프레임워크이다.

post와 get 이용하여 정보 저장하고 불러오기

1. html의 POST부분 설정하기

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

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

클라이언트에서 자료 넣는 부분 체크하여 변수 지정해주기
data에서 지정한 변수(name,comment)를 어떤 데이터로 보낼지 지정(neme_give, comment_give)
성공하면 결과값 알람으로 띄우는 것으로 설정.

2. app 에서 POST로 정보 받아와 db에 저장하기.

@app.route("/homework", methods=["POST"])
def homework_post():
    name_receive = request.form["name_give"]
    comment_receive = request.form["comment_give"]

    doc = {
        'name': name_receive,
        'comment': comment_receive
    }

    db.homework.insert_one(doc)
    return jsonify({'msg':'응원 완료!'})
  1. 클라이언트에서 name_give와 comment_give받아오기
  2. 데이터에 저장할 이름 정하기.
    doc = {
    'name': name_receive,
    'comment': comment_receive
    }
  3. 데이터베이스에 내용 저장하기
    db.homework.insert_one(doc)
  4. return 함수를 종료하고 결과값 돌려보내기. msg 메세지 내용 정하고 msg 변수로 지정

3.app에서 GET 설정

@app.route("/homework", methods=["GET"])
def homework_get():
    comment_list = list(db.homework.find({},{'_id':False}))
    return jsonify({'comments':comment_list})
  1. 저장한 데이터 베이스를 꺼내올 변수 이름 설정(comment_list)
  2. 클라이언트(html)로 보낼 변수 이름 정하고 return하기(comments)

4.html에서 GET 설정

function show_comment() {
            $('#comment-list').empty()
            $.ajax({
                type: "GET",
                url: "/homework",
                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 = `<div class="card">
                                            <div class="card-body">
                                                <blockquote class="blockquote mb-0">
                                                    <p>${comment}</p>
                                                    <footer class="blockquote-footer">${name}</footer>
                                                </blockquote>
                                            </div>
                                        </div>`
                        $('#comment-list').append(temp_html)
                    }
                }
            });
        }
  1. app에서 보낸 comment를 rows로 설정
  2. for문을 통해 리스트를 반복하여 리스트를 꺼내옴.
  3. 어디에 붙일 것인지 변수를 지정하여 설정 여기서는 (temp_html)로 설정. 그리고 백팁을 찍는 것 주의할것
  4. $('#comment-list'붙일곳).append(temp_html지정한 변수이름)

나의 구세주 ys님

맥 적응하고 있는 나에게 certifi의 존재를 알려주신 구세주!
진짜 이거 없었으면 뭐가 문제지...?! 내가 문제인가?! 라면서 좌절 했을것 같다. 이 영광을 ys님에게 돌립니다!!!

profile
나는야 해적이 될거야

0개의 댓글