AWS EC2 서버 구입

  • Ubuntu Server 10.04 LTS 선택
  • Key Pair 생성 후 다운로드

 

AWS EC2 접속하기

  • Git bash 실행해서 다음과 같이 입력
ssh -i 받은키페어드롭 ubuntu@AWS에서EC2의IP
  • Key fingerprint 관련 메세지 → Yes 입력
  • Git bash 종료 시 exit 입력해서 ssh 접속 끊기

 

AWS 보안그룹 설정

  • 해당 EC2 인스턴스 보안그룹 설정

→ 80포트: HTTP 접속을 위한 기본포트

→ 5000포트: flask 기본포트

→ 27017포트: 외부에서 mongoDB 접속을 하기위한 포트

 

AWS EC2 세팅하기

FileZilla 접속

  • new site 만들기
  • SFTP 프로토콜로 설정, Host에 IP 주소 입력, 포트 번호 22
  • user 이름 입력, key file 찾기

EC2 한번에 세팅하기

sudo chmod 755 initial_ec2.sh
./initial_ec2.sh

 

AWS 배포하기

Robo 3T

  • Create 클릭해서 접속 정보 세팅
  • Connection : Name, Address - IP주소, 포트 번호 - 27017
  • Authentication : Databse 이름, User Name과 Password (현재는 test, test임)

FileZilla로 작업한 파일 업로드

  • app.py의 pymongo 세팅 부분을 바꿔서 업로드
client = MongoClient('mongodb://test:test@localhost', 27017)

Flask 패키지 설치 후 실행

pip install flask pymongo
python app.py

 

nohup 설정하기

  • SSH 접속을 종료해도 서버가 계속 실행되도록 함
# 실행하기
nohup python app.py &

# 종료하기
ps -ef | grep 'app.py' # pid값 확인
kill -9 [pid값] # 특정 프로세스 끝내기

나홀로일기장 만들기

 

서버-클라이언트 연결 코드 만들기

  • GET : 데이터 조회(Read) 요청 시 사용
  • POST : 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 시 사용
  • 기본 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)

GET 요청

  • Javascript 로딩 후 실행
$(document).ready(function () {
	alert("!!");
})
  • GET 요청 Ajax 코드
$.ajax({
	type: "GET",
	url: "/diary?sample_give=샘플데이터",
	data: {},
	success: function(response){
		alert(response["msg"])
	}
})
  • GET 요청 API 코드
@app.route('/diary', methods=['GET'])
def show_diary():
	sample_receive = request.args.get('sample_give')
	print(sample_receive)
	return jsonify({'msg': 'GET 연결 완료!'})

POST 요청

  • POST 요청 Ajax 코드
$.ajax({
	type: "POST",
	url: "/diary",
	data: {sample_give:'샘플데이터'},
	success: function(response){
		alert(response['msg'])
	}
})
  • POST 요청 API 코드
@app.route('/diary', methods=['POST'])
def save_diary():
	sample_receive = request.form['sample_give']
	print(sample_receive)
	return jsonify({'msg': 'POST 연결 완료!'})

 

포스팅 API, 리스팅 API 만들기

포스팅 API 만들기

  • 서버
@app.route('/posting', methods=['POST'])
def posting():
	title_receive = request.form['title_give']
	content_receive = request.form['content_give']

	doc = {
		'title': title_receive,
		'content': content_receive
	}
	db.articles.insert_one(doc)

	return jsonify({'msg': '업로드 완료!'})
  • 클라이언트
function posting() {
	let title = $('#title').val()
	let content = $('#content').val()

	$.ajax({
		type: "POST",
		url: "/posting",
		data: {'title_give': title, 'content_give': content},
		success: function (response) {
			alert(response['msg'])
			window.location.reload()
		}
	});
}

리스팅 API 만들기

  • 서버
@app.route('/listing', methods=['GET'])
def listing():
	articles = list(db.articles.find({}, {'_id':False}))
	return jsonify({'articles': articles})
  • 클라이언트
$(document).ready(function() {
	listing()
})

function listing() {
	$.ajax({
		type: "GET",
		url: "/listing",
		data: {},
		success: function (response) {
			let articles = response['articles']
			for (let i = 0; i < articles.length; i++) {
				let title = articles[i]['title']
				let content = articles[i]['content']
				let temp_html = `<div class="card">
	                         <div class="card-body">
	                           <h5 class="card-title">${title}</h5>
                             <p class="card-text">${content}</p>
                           </div>
                         </div>`
				
				$('#cards-box').append(temp_html)
			}
		}
	})
}

 


파일업로드 준비

  • 파일업로드 라이브러리
<script src="https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.js"></script>
  • 파일업로드 코드
bsCustomFileInput.init()

서버 쪽 파일 받기, 클라이언트 쪽 보내기

서버 쪽 파일 받기 코드

file = request.files["file_give"]
save_to = 'static/mypicture.jpg'
file.save(save_to)

클라이언트 쪽 보내기 코드

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()
		}
	});
}

파일 이름 설정 (서버)

f-string

myname = '정예원'
text = f'내 이름은 {myname}'

datetime

from datetime import datetime
now = datetime.now() # 현재 날짜 시간
date_time = now.strftime("%Y-%m-%d-%H-%M-%S") # 원하는 형태로 변환하기

파일 이름 변경해서 저장하기

  • 확장자 추출
extension = file.filename.split('.')[-1]
  • 새로운 이름 짓고 저장하기
now = datetime.now() # 현재 날짜 시간
mytime = now.strftime("%Y-%m-%d-%H-%M-%S") # 원하는 형태로 변환하기
filename = f'file-{mytime}'

save_to = f'static/{filename}.{extension}'
file.save(save_to)
  • 변경된 파일 이름으로 DB에 저장하기
doc = {
	'title': title_receive,
	'content': content_receive,
	'file': f'{filename}.{extension}',
}
db.diary.insert_one(doc)

카드 목록 출력 (클라이언트)

function listing() {
    $.ajax({
        type: "GET",
        url: "/listing",
        data: {},
        success: function (response) {
            if (response["result"] == "success") {
                let articles = response['articles']
                for (let i = 0; i < articles.length; i++) {
                    let title = articles[i]['title']
                    let content = articles[i]['content']
                    let file = articles[i]['file']

                    let temp_html = `<div class="card">
                                        <img src="../static/${file}" class="card-img-top">
                                        <div class="card-body">
                                            <h5 class="card-title">${title}</h5>
                                            <p class="card-text">${content}</p>
                                        </div>
                                    </div>`

                    $('#cards-box').append(temp_html)
                }
            }
        }
    });
}

웹서비스 동작 원리

  • 클라이언트가 요청하면 서버가 요청을 받아서 무언가를 돌려준다

API란?

  • 서버가 요청을 받기 위해 뚫어놓은 창구
  • POST (주로 데이터 수정 시), GET (주로 데이터 가져올 때) 등 여러 타입의 요청이 존재

jQuery란?

  • Javascript의 라이브러리 중 하나로 HTML 조작을 쉽게 한다
  • 사용하기 위해서 import가 필요하다

Ajax란?

  • 서버 통신을 위해 쓰인다
$.ajax({
	type: "GET",
	url: "요청할 url",
	data: {},
	success: function(response) {
		// 서버가 준 데이터가 response에 담긴다
	}
})

Flask란?

  • 서버를 만드는 프레임워크
  • 아래 코드를 run 하면 localhost 5000으로 접속 가능
from flask import Flask, render_template, jsonfiy, 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)

 

프로젝트 세팅

  • 프론트엔드 → Bootstrap, 백엔드 → Python으로 된 Flask 라이브러리 이용
  • templates, static 폴더와 app.py 생성
  • Windows : file → settings → Python Interpreter → + 버튼
  • Mac : pycharm → preferences → Python Interpreter → + 버튼
  • requests, bs4, flask, pymongo 패키지 설치

PyCharm 라이센스 등록하기

PyCharm 라이센스 코드 발급

  • 스파르타코딩클럽을 통해 라이센스 코드 발급
  • 4개월 간 PyCharm Professional 버전을 무료로 사용 가능

JetBrains 로그인

  • JetBrains 접속해서 로그인 완료 : https://account.jetbrains.com/licenses
  • Purchase Product license(s) 클릭 → PyCharm 오른쪽 끝의 Buy new license 클릭
  • Proceed as new customer 클릭 → Have a discount code? 클릭
  • 파이참 라이센스 코드 입력 완료 후 Place Order 클릭
  • PyCharm Pro 실행해서 email, password 입력 후 Activate

 

필수 프로그램 설치

PyCharm Professional 설치

JetBrains 회원가입

MongoDB 설치

  • 다운로드 링크 : https://www.mongodb.com/try/download/community
  • MongoDB Community Server 탭 → Version 4.4.1 / Platform : Windows / Package : MSI
  • 설치 진행 시 Custom 클릭해서 C:\data\db\ 선택
  • Install MongoDB Compass 선택 해제 후 설치
  • 환경 변수 - 시스템 변수 - Path 편집해서 C:\data\db\bin 추가
  • cmd 창에서 연결 확인
mongod --install --serviceName MongoDB --serviceDisplayName MongoDB --dbpath C:\data\db --logpath C:\data\db\log\mongoservice.log --logappend
mongo

Robo 3T 설치

Filezilla 설치

기타

  • AWS 가입하기
  • Python 설치
  • Git bash 설치

+ Recent posts