[Python + Robo 3T] 스파르타 코딩 3주 차 5번째 수업 - 2

안영우·2020년 10월 18일
0

✏️ 서론

다음으로 CRUD 에 대해 알아보자.
현재 시장에 출시되어 있는 모든 서비스는 CRUD 를 기반으로 만들어진다.
CRUD 는 크게 4가지로 나뉜다. CRUD 가 뭘까?
인스타그램을 쉽게 예로 들어보자. 인스타그램은 다음과 같은 기능을 수행할수있다. 나중에 앱, 웹개발 할 때 CRUD 를 기본 세트라고 생각하면 편하다.

Create(생성) : 게시물 생성
Read(읽기) : 게시물 보기
Update(갱신) : 게시물 수정
Delete(삭제) : 게시물 삭제

오늘 사용 할 기능은 Pythonpymongo 패키지로 제어하고 Robo 3T로 확인하는 과정을 거치겠다.

Robo 3TGUI(Graphic User Interface) 기능이 없는 mongoDB 내부를 살펴보기 위한 프로그램이다.

DB(DataBase) 는 크게 2가지 종류가 있다.

  • RDBMS(SQL) : 행/열의 생김새가 정해진 엑셀에 데이터를 저장하는것과 유사하다. 틀이 매우 정형화 되어있어 중간에 데이터를 추가하려면 No SQL보다 어렵다. 회원 개인정보를 보관하거나 서비스 제작시에 많이 쓰인다.
    대표적으로 postgreSQL MySQL 등이 있다.

  • No SQL : 딕셔너리 형태로 data를 저장하는 DB이다. 자유로운 형태의 데이터 적재에 유리한 대신, 일관성이 부족하다.
    대표적으로 MongoDB가 있다.


✏️ 본론

이제 본격적으로 pymongo 를 사용해서 MongoDB 를 조작해보자.
서론에서 언급했던 CRUD 내용을 기반으로 배워보자.

1. Create

from pymongo import MongoClient

# Mongo_Client의 서버, 주소 입력
client = MongoClient('localhost', 27017) 

# Roto 3T안에 있는 db의 이름은 ' dbsparta '
db = client. dbsparta 

# 이번에 사용할 딕셔너리형은 다음과 같다.
db.users.insert_one({'name': '덤블도어', 'age': 116})
db.users.insert_one({'name': '맥고나걸', 'age': 85})
db.users.insert_one({'name': '스네이프', 'age': 60})
db.users.insert_one({'name': '해리', 'age': 40})
db.users.insert_one({'name': '허마이오니', 'age': 40})
db.users.insert_one({'name': '론', 'age': 40})

해당코드를 실행한 후 Robo 3T 에 접속하면 다음과 같다.

2. Read

from pymongo import MongoClient

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

all_users = list(db.users.find({}))
print(all_users)
print()

for users in all_users:
    print(users)
    
👉🏽 결과
[{'_id': ObjectId('5f8c4a0390241f4279342e0c'), 'name': '덤블도어', 'age': 19}, {'_id': ObjectId('5f8c4a0390241f4279342e0d'), 'name': '맥고나걸', 'age': 85}, {'_id': ObjectId('5f8c4a0390241f4279342e0e'), 'name': '스네이프', 'age': 60}, {'_id': ObjectId('5f8c4a0390241f4279342e0f'), 'name': '해리', 'age': 40}, {'_id': ObjectId('5f8c4a0390241f4279342e10'), 'name': '허마이오니', 'age': 40}]

{'_id': ObjectId('5f8c4a0390241f4279342e0c'), 'name': '덤블도어', 'age': 19}
{'_id': ObjectId('5f8c4a0390241f4279342e0d'), 'name': '맥고나걸', 'age': 85}
{'_id': ObjectId('5f8c4a0390241f4279342e0e'), 'name': '스네이프', 'age': 60}
{'_id': ObjectId('5f8c4a0390241f4279342e0f'), 'name': '해리', 'age': 40}
{'_id': ObjectId('5f8c4a0390241f4279342e10'), 'name': '허마이오니', 'age': 40}

3. Update

from pymongo import MongoClient

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

# 'name' 값 외에도 다른 값을 넣을 수 있다.
magician = list(db.users.find({'name' : '덤블도어'}))
print(magician)
print()

# 'name'의 'age'값을 변경한다.
db.users.update_one({'name' : '덤블도어'}, {'$set' : {'age' : 19}})
user = db.users.find_one({'name' : '덤블도어'})
print(user)

👉🏽결과 # 기존 119세에서 19세로 변경된것을 볼 수 있다.
[{'_id': ObjectId('5f8c4a0390241f4279342e0c'), 'name': '덤블도어', 'age': 116}]

{'_id': ObjectId('5f8c4a0390241f4279342e0c'), 'name': '덤블도어', 'age': 19}

4. Delete

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

db.users.delete_one({'name' : '론'})

user = db.users.find_one({'name' : '론'})
print(user)

👉🏽결과
None
  • 실제 개발시 데이터를 삭제하면 복구가 어렵기 때문에 삭제 보다
    사용하지 않음으로 처리하는경우가 많다.

📍 예제

1. web_scraping 결과를 MongoDB 에 저장하는 코드를 작성해라.

import requests
from bs4 import BeautifulSoup
from pymongo import Mongoclient

# MongoDB 코드
client = MongoClient('localhost', 27017)
db = client.dbsparta

# 크롤링 코드
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://movie.naver.com/movie/sdb/rank/rmovie.nhn?sel=pnt&date=20200716', headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')

movies = soup.select('#old_content > table > tbody > tr')

for movie in movies:
    a_tag = movie.select_one('td.title > div > a')
    if a_tag is not None:
        rank = movie.select_one('td:nth-child(1) > img')['alt'] 
        title = a_tag.text
        star = movie.select_one('td.point').text
        print(rank, title, star)
        
        doc = {
        	'rank' = rank
            	'title' = title
                'star' = star
              }
       db.movies.insert_one(doc)
       
👇🏽 결과

  • 1 - 1. 영화 제목: 월-E 의 평점을 출력해라.
from pymongo import MongoClient

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

# movie_target에 title을 하나 저장한다.
movie_target = db.movies.find_one({'title': '월-E'})

# movie_score에 해당title의 star를 저장한다.
movie_score = movie_target['star']
print(movie_score)

👉🏽 결과
9.41
  • 1 - 2. 영화 제목: 월-E 와 평점이 같은 영화를 출력해라.
from pymongo import MongoClient

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

movie_target = db.movies.find_one({'title': '월-E'})
movie_score = movie_target['star']

all_movies = db.movies.find({'star': movie_score})
for all_movie in all_movies:
    print(all_movie['title'])
    
👉🏽 결과
월-E
나 홀로 집에
아이즈 온 미 : 더 무비
  • 1 - 3. 영화 제목: 월-E 와 평점이 같은 영화들의 평점을 0점으로 만들어라.
from pymongo import MongoClient

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

target_movie = db.movies.find_one({'title': '월-E'})
target_star = target_movie['star']
print(target_star)

db.movies.update_many({'star': target_star}, {'$set': {'star': 0}})

👉🏽 결과
0

✏️ 결론

[추석특집] 파이썬 혼자놀기 과정 에서 배운 내용을 토대로 DB CRUD 방식을 더하기만 하면 되는 내용이라 딱히 난이도가 높지 않다.

다만, DB를 다루는 작업이 능숙치 못해 시간이 조금 걸린다.
지금은 No SQL 로 실습을 해봤는데, 다음에는 현업에서 많이 사용되는 RDBMS(SQL) 로 다뤄봤으면 좋겠다.

다음시간에는 개발자들의 놀이터인 Git-hub 에 대해서 배운다.
처음 배우는 과정이 어렵다는 얘기가 많은데, 얼른 적응했으면 좋겠다.

profile
YW_Tech

0개의 댓글