내배캠 주요 학습/매일 공부

1주차 미니 프로젝트 총 정리

chaeyoung- 2023. 5. 19. 19:27

진행 일자 : 20230515 - 20230519  총 몰입 시간 : 64시간

Main Page & Personal Page

https://github.com/uiseongsang/ggLand

 

GitHub - uiseongsang/ggLand: 우리만의 이야기를 담을 수 있는 ”팀 소개 웹페이지”

우리만의 이야기를 담을 수 있는 ”팀 소개 웹페이지”. Contribute to uiseongsang/ggLand development by creating an account on GitHub.

github.com

회고록 : 2023.05.19 - [내일배움캠프 공부/매일 공부] - 팀 소개 페이지 - 회고록 : 6조 개새기

 

팀 소개 페이지 - 회고록 : 6조 개새기

1. 한 주의 흐름 1) 한 일 시연 영상 : https://youtu.be/mK0RekyzNeg 프로젝트 명 : 각 팀원의 아일랜드 소개 페이지 필수 작업 : 방명록 CRUD, 메인 및 상세 페이지 UI/UX 추가 작업 : 수정 및 삭제 기능 구현

cdev.tistory.com

프로젝트 정보 : 2023.05.16 - [내일배움캠프 공부/매일 공부] - 팀소개 페이지 작업 과정 - ggLand :

 

팀소개 페이지 작업 과정 - ggLand :

20230516 09:23 am - https://github.com/uiseongsang/ggLand S.A 링크: https://velog.io/@uiseongsang/내일배움캠프-A-6조개새기조-개발자-새내기조 팀 프로젝트 주제 : 팀원 소개 페이지 서비스 이름 개새랜드 - 개발자 새

cdev.tistory.com

프로젝트 결과 : 2023.05.19 - [내일배움캠프 공부/매일 공부] - 팀소개 페이지 프로젝트 결과

 

팀소개 페이지 프로젝트 결과

시연 영상 : https://youtu.be/mK0RekyzNeg

cdev.tistory.com

 

python을 활용한 웹 페이지 생성은 이번이 처음이였습니다. Java&Spring이 아닌 다른 언어를 통해 페이지를 구성하는 것이 조금 간편했던 것 같습니다. 다음에는 조금 더 완성도가 높은 프로젝트를 진행하기 위해 노력할 것 입니다. 짧은 시간동안 협업을 하다보니 시간이 더욱 오래 걸린 것 같습니다. 또한, 저도 해당 프로젝트를 통해서 부족한 부분이 많음을 깨달았습니다. 이번 프로젝트를 통해 코드컨벤션 및 코드 작성시 유의사항 및 통상적으로 지키는 규칙 등을 파악할 수 있었습니다. 또한, 프론트엔드 부분도 시간을 투자하면 잘은 못하더라고 기본적인 틀은 잘 자리잡아 만들수 있게 되었습니다.

 

 

문제1. git부분에서 많은 문제가 있었습니다.

 

문제2. 각 팀원들의 DB를 참조하기 위해서 table명을 변수로 받아 해당 변수의 테이블에 접근하는데에 어려움을 겪었습니다. 해결방법은 아래와 같습니다. 

db.members.insert_one(doc)

예를 들어 members라는 테이블에 접근하기 위한 상단의 코드를

tableName = "members"
db.tableName.insert_one(doc)

이와 같은 코드로는 실행이 되지 않습니다.

이유는 tableName이라는 변수는 현재 String 타입이고, 테이블명이 들어갈 자리에는 collection이기 때문입니다.

tableName = "members"
db.get_collection(tableName).insert_one(doc)

이와 같이 변경하여 해결 하였습니다.

db.get_collection()을 이용하여 db를 참조할 수 있음을 새롭게 알게되었습니다.

 

ProjectCode의 일부 발췌

# 방명록 데이터 DB에 저장
@app.route("/api/comment-save", methods=["POST"])
def comment_post():
    #commentId_receive = request.form['commentId_give']
    commentName_receive = request.form['commentName_give']
    commentContent_receive = request.form['commentContent_give']
    commentPassword_receive = request.form['commentPassword_give']
    islandId = request.form['islandId_give']

    date = str(datetime.now().strftime('%Y-%m-%d %H:%M'))
    
    doc = {
        #'commentId':commentId_receive,
        'commentName' : commentName_receive,
        'commentContent' : commentContent_receive,
        'commentPassword' : commentPassword_receive,
        'commentDate' : date}
    
    print(islandId)
    # 본인 table명으로 변경해주세요
    tableStr = islandId + "_post"
    
    db.get_collection(tableStr).insert_one(doc)
    return jsonify({'msg':'아일랜드에 발자취를 남겼다!'})

 

 

내가 구현한 부분 :

- 방명록 작성 및 출력 form

- 방명록 수정 form 배치

- 방명록 DB 참조 후 페이지에 출력

- 아일랜드별 좋아요 기능 

- 방명록 수정, 삭제 시 비밀번호 확인

 

서버 코드는 더보기를 눌러주세요

더보기
from urllib import parse
from datetime import datetime
from bson.objectid import ObjectId
from flask import Flask, render_template, request, jsonify, redirect
app = Flask(__name__)

from pymongo import MongoClient
import certifi
ca=certifi.where()

client = MongoClient('mongodb+srv://sparta:test@limchaeyoung.boi4rwj.mongodb.net/?retryWrites=true&w=majority')
db = client.dbsparta

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/playGround')
def show_playGround():
    return render_template('playGround.html')

@app.route('/detailUS')
def show_detailUS():
    return render_template('detailUS.html')

@app.route('/detailCY')
def show_detailCY():
    return render_template('detailCY.html')

@app.route('/detailSI')
def show_detailSI():
    return render_template('detailSI.html')

@app.route('/detailSY')
def show_detailSY():
    return render_template('detailSY.html')

@app.route('/detailHY')
def show_detailHY():
    return render_template('detailHY.html')

# 좋아요 불러오기
@app.route("/api/island-get-liked", methods=["GET"])
def island_getlike():
    # islandId_receive에 맞는 cnt 값 가져오기
    all_likeCnts = list(db.island.find({},{'_id':False}))
    return jsonify({'result': all_likeCnts})


# 좋아요 추가하기
@app.route("/api/island-add-liked", methods=["POST"])
def island_addlike():
    id_receive = request.form['id_give']
    cnt_receive = request.form['cnt_give']
    
    print(id_receive,cnt_receive)
    
    db.island.update_one({'islandId':id_receive},{'$set':{'islandLikeCnt':cnt_receive}})
    return jsonify({'msg':'complete'})
    

# 방명록 데이터 DB에 저장
@app.route("/api/comment-save", methods=["POST"])
def comment_post():
    #commentId_receive = request.form['commentId_give']
    commentName_receive = request.form['commentName_give']
    commentContent_receive = request.form['commentContent_give']
    commentPassword_receive = request.form['commentPassword_give']
    islandId = request.form['islandId_give']

    date = str(datetime.now().strftime('%Y-%m-%d %H:%M'))
    
    doc = {
        #'commentId':commentId_receive,
        'commentName' : commentName_receive,
        'commentContent' : commentContent_receive,
        'commentPassword' : commentPassword_receive,
        'commentDate' : date}
    
    print(islandId)
    tableStr = islandId + "_post"
    
    db.get_collection(tableStr).insert_one(doc)
    return jsonify({'msg':'아일랜드에 발자취를 남겼다!'})


# 방명록 내용 출력
@app.route("/api/comment", methods=["POST"])
def comments_get():        
    islandId = request.form['islandId_give']
    tableStr = islandId + "_post"
    
    all_comments = list(db.get_collection(tableStr).find({},
    {'_id':True, 'commentId':True, 'commentName':True, 'commentDate':True, 'commentContent':True, 'commentPassword':True}))
    
    for comment in all_comments:
        comment['_id'] = str(comment['_id'])
    #print(all_comments)
    return jsonify({'result': all_comments})


# 방명록 내용 수정
@app.route("/api/update-comment", methods=["POST"])
def comment_update():
    receive_id = str(request.form['_id_give'])
    receive_target_name = request.form['targetname_give']
    receive_target_content = request.form['targetcontent_give']
    islandId = request.form['islandId_give']
    
    # string에서 ObjectId로 변경
    comment_id = ObjectId(receive_id)
    
    tableStr = islandId + "_post"
    db.get_collection(tableStr).update_one({'_id': comment_id}, {'$set': {'commentName': receive_target_name, 'commentContent': receive_target_content}})
    return jsonify({'msg':'나의 발자취를 고쳤다!'})


# 방명록 삭제 
@app.route("/api/delete-comment", methods=["POST"])
def delete_post():
    receive_id = str(request.form['_id_give']) # request.form
    islandId = request.form['islandId_give']
    
    tableStr = islandId + "_post"
    db.get_collection(tableStr).delete_one({'_id' : ObjectId(receive_id)})
    return jsonify({'msg':'나의 발자취를 삭제했다!'})


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

 

Front-end 

HTML

id :소문자, 카멜스타일 변수(EX: imageCount)

'commentId' -- (식별)고유값

'commentName' --작성자

'commentDate' -- 작성일

'commentContent' --내용

class: 아이디와 시각적 구분을 위해 하이픈 표기법 을 사용합니다.

많은 FrontEnd 개발 프레임워크 및 javascipt 플러그인의 코딩 스타일도 하이픈 표기법을 사용하고 있으며, 프로젝트의 코드의 일관성을 유지하기 위해서도 하이픈 표기법 사용을 권장합니다. 

빈줄 : 그룹되어 있는 tag 들을 구분하기 위하여 코드 간 1줄의 빈 줄을 사용하는 경우가 있지만, 이 경우 주석 사용 미권장.

주석 : 주석 기호와 내용 사이에는 반드시 공백이 한 칸 필수. 시작 주석과 끝 주석 모두 작성 권장.

 

CSS

네이밍 컨벤션에는 다양한 규칙이 있지만, 이번 포스트에서는 프론트앤드, 특히 css 쪽에서 자주 사용하는 BEM (Block Element Modifier) 방법론에 대해서 정리하려 합니다.

BEM은 전체적으로 이렇게 이루어집니다.

  • 항상 영어 소문자만을 사용합니다. 카멜 케이스 등은 사용하지 않습니다.
  • 일반적으로 한 요소는 하이픈으로 연결합니다. (예를 들면 input-text, button-submit, modal-alert 등등.. )
  • 네이밍의 조합은 형태-의미-순서-상태 순으로 사용합니다. (예시 button-submit-03-disable)
  • 언더스코어는 파일, 폴더, 이미지 등에만 사용합니다(image_elysia_asset_01.png)
  • 숫자를 사용할 때는 확장성을 고려해 1, 2 이런 식으로 표현하지 않고 01, 02, 03… 혹은 001, 002, 003처럼 사용합니다. 앞에 0을 붙이지 않으면, 이미지 정렬 시 1 다음에 2가 오지 않고 10이 오는 등, 정렬 순서가 엉망이 될 수 있기 때문입니다.

 

 

JS

 

Back-end

<REST API>

REST API URL 규칙

  • 인터페이스 일관성 : 일관적인 인터페이스로 분리되어야 한다.
  • 무상태 : 각 요청간 클라이언트의 context, 세션과 같은 상태 정보를 서버에 저장하지 않는다.
  • 캐시 처리 기능 : 클라이언트는 응답을 캐싱할수 있어아한다. 캐시를 통해 대량의 요청을 효율적으로 처리한다.
  • 계층화 : 클라이언트는 대상 서버에 직접 연결되어있는지, Proxy를 통해서 연결되었는지 알 수 없다.
  • Code on demand : 자바 애플릿이나 자바스크립트의 제공을 통해 서버가 클라이언트를 실행시킬 수 있는 로직을 전송하여 기능을 확장시킬수 있다.
  • 클라이언트/서버 구조 : 아키텍처를 단순화 시키고 작은 단위로 분리함으로써 클라이언트 서버의 각 파트가 독립적으로 구분하고 서로간의 의존성을 줄인다.

REST 구성요소

  1. 자원(Resource) : HTTP URL
  2. 자원에 대한 행위 : HTTP Method
  3. 자원에 대한 표현 : Representation

REST API 설계 Rules

1. 소문자를 사용한다.

2. 언더바(_) 대신 하이픈(-)을 사용한다.

3. 마지막에 슬래시(/)를 포함하지 않는다.

4. 행위를 포함하지 않는다.

5. 파일 확장자는 URL에 포함시키지 않는다.

6. 전달하고자 하는 명사를 사용하되, 컨트롤 자원을 의미하는 경우 예외적으로 동사를 사용한다.

7. URI에 작성되는 영어를 복수형으로 작성한다.

자세한 설명은 블로그: https://dev-cool.tistory.com/32

 

 

API 명세서

Function Method URL Request Response

좋아요 출력 : [GET]  /api/island-get-liked  

좋아요 추가 : [POST]  /api/island-add-liked

방명록 저장. [POST]  /api/comment-save 

방명록 출력. [POST] /api/comment

방명록 수정. [POST ] UPDATE /api/update-comment 

방명록 삭제. [POST] DELETE /api/delete-comment 

 

<<Env version>>

bootstracp - 5.0.2

jQuery - 3.5.1

 

<<python package>>

Flask - 2.3.2

requests - 2.30.0

pymongo - 4.3.3

bs4 - 0.0.1