웹개발 플러스 1주차

귀찮Lee·2022년 3월 28일
0

□ 웹개발 플러스 (1주차)

22.03.28(월)

◎ 개발환경 구축하기

  • Pycharm, AWS, Python, mongoDB, Robo3T, Git bash, Filezilla

◎ 이론 복습

  • 서버(server) : 특수한 컴퓨터가 아님, 서버는 요청을 받으면 HTML+CSS+JavaScript 파일을 주기도 하고, JSON 형식으로 데이터를 주기도 함.

  • API: 서버가 요청을 받게 위해 뚫어놓은 '창구', 요청에는 POST(주로 데이터를 수정할 때), GET(주로 데이터를 가져올 때) 요청 등 여러가지 타입이 있다

  • HTML, CSS, JS:
    간략하게 이야기하여 HTML은 뼈대 / CSS는 꾸미기 / JavaScript는 움직이게 하는 것

  • JQuery: JavaScript의 라이브러리로, HTML 조작을 쉽게 함
    id로 이름표를 붙여주고(id="아이디"), $('#아이디').val() 과 같이 input 박스의 값을 가져올 수 있다.

-Ajax: 서버 통신을 위해 쓰임, 기본 예제문을 응용해서 사용

$.ajax({
    type: "GET",
    url: "요청할 URL",
    data: {},
    success: function (response) {
        // 서버가 준 데이터가 response에 담깁니다!
    }
})

-Flask: 서버를 만드는 프레임워크, 누군가 만들어둔 틀 안에서 코딩

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

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

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

◎ f-string

  • python에서 중간에 변수값을 넣고싶을 때 사용.
# f-string
name= '홍길동'
age = '30'

# 위 상황을 대체해 아래 상황처럼 사용
hello = '제 이름은 ' + name + '이구요.'
hello = f'제 이름은 {name} 이구요. 나이는 {age}입니다.'

print(hello)
# 제 이름은 홍길동 이구요. 나이는 30입니다.

datetime 사용

  • 현재 시간을 이용하고 싶을 때 사용
from datetime import datetime

today = datetime.now()
print(today)

mytime = today.strftime("%Y_%m_%d_%H_%M_%S")
print(mytime)

◎ 사진 업로드

  • Client
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- file upload library -->
<script src="https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.js"></script>

<script>
  function posting() {
            let title = $('#title').val()
            let content = $("#content").val()

            let file = $('#file')[0].files[0]
            let form_data = new FormData()

            form_data.append("file_give", file)
            form_data.append("title_give", title)
            form_data.append("content_give", content)

            $.ajax({
                type: "POST",
                url: "/diary",
                data: form_data,
                cache: false,
                contentType: false,
                processData: false,
                success: function (response) {
                    alert(response["msg"])
                    window.location.reload()
                }
            });
        }
</script>

<body>
  <div class="custom-file">
     <input type="file" class="custom-file-input" id="file">
     <label class="custom-file-label" for="file">사진 선택하기</label>
  </div>
</body>
  • Server
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)

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

from datetime import datetime


@app.route('/diary', methods=['POST'])
def save_diary():
    title_receive = request.form['title_give']
    content_receive = request.form['content_give']

    file = request.files["file_give"]	
    #확장자 추출
    extension = file.filename.split('.')[-1]
    # datetime을 통해 파일 이름 구분
    today = datetime.now()
    mytime = today.strftime("%Y_%m_%d_%H_%M_%S")
    filename = f'file-{mytime}'
    # static 폴더에 사진 저장
    save_to = f'static/{filename}.{extension}'
    file.save(save_to)

    upload_date = today.strftime("%Y-%m-%d")

    doc = {
        'title': title_receive,
        'content': content_receive,
        'file': f'{filename}.{extension}',
        'time': upload_date
    }
    db.diary.insert_one(doc)

    return jsonify({'msg': '저장 완료!'})
profile
배운 것은 기록하자! / 오류 지적은 언제나 환영!

0개의 댓글