MSA (Monolithic Architecture)란
소프트웨어의 모든 구성요소가 한 프로젝트에 통합되어있는 형태로 독립적으로 배포 가능한 각각의 기능을 수행하는 서비스로 구성된 프레임워크라고 할 수 있다.
데이터베이스 DATEBASE (RDBMS vs NoSQL)
Elastic Beanstalk에 배포해서 RDS, Python 연동해보기
2-1 Pycharm 옆에 Datebase > Data Sourse > MySQL 클릭
2-2 Information 우클릭 후 스키마 생성
2-3 이름 설정하고 Preview를 아래와 같이 작성
2.4 생성 완료 > query consoles > jump to query console files 클릭
2.5 아래의 내용 작성하고 실행
3.1 RDS의 인바운드 규칙을 추가한다.
3.2 사용한 코드
( 백앤드 코드 )
import boto3
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
import os
from flaskext.mysql import MySQL
application = Flask(__name__)
# cors
cors = CORS(application, resources={r"/*": {"origins": "*"}})
# mysql
mysql = MySQL()
application.config['MYSQL_DATABASE_USER'] = os.environ["MYSQL_DATABASE_USER"]
application.config['MYSQL_DATABASE_PASSWORD'] = os.environ["MYSQL_DATABASE_PASSWORD"]
application.config['MYSQL_DATABASE_DB'] = os.environ["MYSQL_DATABASE_DB"]
application.config['MYSQL_DATABASE_HOST'] = os.environ["MYSQL_DATABASE_HOST"]
mysql.init_app(application)
@application.route('/')
def main():
return "핵심 쏙쏙 AWS"
@application.route('/fileupload', methods=['POST'])
def file_upload():
file = request.files['file']
s3 = boto3.client('s3',
aws_access_key_id=os.environ["AWS_ACCESS_KEY_ID"],
aws_secret_access_key=os.environ["AWS_SECRET_ACCESS_KEY"]
)
s3.put_object(
ACL="public-read",
Bucket=os.environ["BUCKET_NAME"],
Body=file,
Key=file.filename,
ContentType=file.content_type
)
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute("insert into file(file_name) value('" + file.filename + "')")
conn.commit()
conn.close()
return jsonify({'result': 'success'})
@application.route('/files', methods=['GET'])
def files():
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute("SELECT file_name from file")
data = cursor.fetchall()
conn.close()
return jsonify({'result': 'success', 'files':data})
if __name__ == '__main__':
application.debug = True
application.run()
(프론트앤드 코드)
<!Doctype html>
<html lang="ko">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<!-- JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<!-- 구글폰트 -->
<link href="https://fonts.googleapis.com/css?family=Stylish&display=swap" rel="stylesheet">
<title>이쁘게 | 꾸미기</title>
<!-- style -->
<style type="text/css">
* {
font-family: 'Stylish', sans-serif;
}
.wrap {
width: 900px;
margin: auto;
}
.comment {
color: blue;
font-weight: bold;
}
#post-box {
width: 500px;
margin: 20px auto;
padding: 50px;
border: black solid;
border-radius: 5px;
}
</style>
<script>
$(document).ready(function(){
getFiles();
})
function save() {
var form_data = new FormData($('#upload-file')[0]);
$.ajax({
type: 'POST',
url: '{EB URL}/fileupload',
data: form_data,
processData: false,
contentType: false,
success: function (data) {
alert("파일이 업로드 되었습니다!!");
location.reload();
},
});
}
function getFiles() {
$.ajax({
type: 'GET',
url: '{EB URL}/files',
success: function (data) {
for(let i = 0 ; i < data['files'].length ; i++){
makeCard(data['files'][i]);
}
},
});
}
function makeCard(data){
let card = ` <div class="card">
<div>
<img class="card-img-top"
src="http://djocwjyh5wkd4.cloudfront.net/${data}"
alt="Card image cap">
<p class="card-text comment">${data}</p>
</div>
</div>`;
$("#cards-box").append(card);
}
</script>
</head>
<body>
<div class="wrap">
<div class="jumbotron">
<h1 class="display-4">메모장! 완료!!</h1>
<p class="lead">중요한 이미지를 저장해두고, 나중에 볼 수 있는 공간입니다</p>
<hr class="my-4">
</div>
<div id="post-box" class="form-post">
<div>
<div class="form-group">
<form id="upload-file">
<label for="post-url">이미지 파일</label>
<input type="file" name="file"/>
</form>
</div>
<button type="button" class="btn btn-primary" onclick="save()">저장</button>
</div>
</div>
<div id="cards-box" class="card-columns">
</div>
</div>
</body>
</html>
3.3 라이브러리 추가
로컬(local) python pip install install flask-mysql
EB 배포 pip freeze > requirements.txt
3.4 환경변수 추가