AWS 4 (python 연동 코드)

호호빵·2022년 4월 27일
0

AWS

목록 보기
4/6

RDS, Python 연동

  • RDS 보안 그룹에 아이피 0.0.0.0/0 추가(러프하게 사용하기 위해)
  • 백엔드 application.py 코드 추가, 프론트 index.html 코드 추가
  • 백엔드에 라이브러리 추가
    (pip install install flask-mysql , 로컬)
    (pip freeze > requirements.txt , EB 배포용)
  • EB에 환경변수에 4가지 추가
  • commit and push, cloudfront 주소로 확인
# application.py

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

# MYSQL_DATABASE_USER
# MYSQL_DATABASE_PASSWORD
# MYSQL_DATABASE_DB
# MYSQL_DATABASE_HOST  환경변수 
# index.html
<!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>스파르타코딩클럽 | 나홀로 메모장111</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>


ElasticCache, Python 연동

RDS와 달리 외부에서 접속 불가능
내 컴퓨터가 아닌 배포를 해서 같은 VPC내의 인스턴스에서 확인해야 함.

  • 백엔드 application.py 코드 추가, 프론트 index.html 코드 추가
  • 백엔드에 라이브러리 추가
    (pip install redis , 로컬)
    (pip freeze > requirements.txt , EB 배포용)
  • EB 환경변수에 REDIS_HOST 추가
  • commit and push, cloudfront 주소로 확인
# application.py

import boto3
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
import os
from flaskext.mysql import MySQL
import redis  # 로컬코드

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)

# redis
db = redis.Redis(os.environ["REDIS_HOST"], decode_responses=True)


@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()


    cursor.execute("SELECT count(*) from file")
    data = cursor.fetchone()
    conn.close()
    db.set("fileCount", data[0])

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

@application.route('/file/count', methods=['GET'])
def file_count():
    return jsonify({'result': 'success', 'count':db.get("fileCount")})

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>스파르타코딩클럽 | 나홀로 메모장111</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(){
            getCount();
            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);
        }

        function getCount() {
            $.ajax({
                type: 'GET',
                url: '{EB URL}/file/count',
                success: function (data) {
                    $("#count").html(data.count);
                },
            });
        }
    </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>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="#">총 파일갯수:<span id="count"></span></a>
    </nav>
    <div id="cards-box" class="card-columns">
    </div>
</div>
</body>

</html>
profile
하루에 한 개념씩

0개의 댓글