본문 바로가기
DEV/Web 개발

파이썬 웹 프로그래밍 :: aws 활용 웹 퍼블리싱

by 올커 2022. 7. 24.

파이썬 웹 프로그래밍_aws 활용 웹 퍼블리싱


들어가면서..

 aws 서버 구매, Flask 서버 셋팅 및 실행, 도메인 연결을 통한 웹 퍼블리싱 마무리

1. 사전 준비

· FileZilla 설치 : https://filezilla-project.org/download.php
· gabia 가입 및 도메인 구매 : 할인이벤트(500원/1년)를 진행하는 도메인으로 구매

2. 실습 프로젝트. 버킷리스트 

 1) app.py

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

from pymongo import MongoClient
client = MongoClient('내 URL 입력')
db = client.dbsparta

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

@app.route("/bucket", methods=["POST"])
def bucket_post():
    bucket_receive = request.form['bucket_give']

    bucket_list = list(db.bucket.find({}, {'_id': False}))
    count = len(bucket_list) +1

    doc = {
        'num' : count,
        'bucket' : bucket_receive,
        'done' : 0
    }
    db.bucket.insert_one(doc)

    print(bucket_receive)
    return jsonify({'msg': '등록 완료!'})

@app.route("/bucket/done", methods=["POST"])
def bucket_done():
    num_receive = request.form['num_give']
    db.bucket.update_one({'num': int(num_receive)}, {'$set': {'done': 1}})
    return jsonify({'msg': '버킷 완료!'})

@app.route("/bucket", methods=["GET"])
def bucket_get():
    bucket_list = list(db.bucket.find({}, {'_id': False}))
    return jsonify({'buckets': bucket_list})

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

 1) index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>

    <link href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap" rel="stylesheet">

    <title>인생 버킷리스트</title>

    <style>
        * {
            font-family: 'Gowun Dodum', sans-serif;
        }
        .mypic {
            width: 100%;
            height: 200px;

            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://images.unsplash.com/photo-1601024445121-e5b82f020549?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1189&q=80');
            background-position: center;
            background-size: cover;

            color: white;

            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        .mypic > h1 {
            font-size: 30px;
        }
        .mybox {
            width: 95%;
            max-width: 700px;
            padding: 20px;
            box-shadow: 0px 0px 10px 0px lightblue;
            margin: 20px auto;
        }
        .mybucket {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-between;
        }

        .mybucket > input {
            width: 70%;
        }
        .mybox > li {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;

            margin-bottom: 10px;
            min-height: 48px;
        }
        .mybox > li > h2 {
            max-width: 75%;
            font-size: 20px;
            font-weight: 500;
            margin-right: auto;
            margin-bottom: 0px;
        }
        .mybox > li > h2.done {
            text-decoration:line-through
        }
    </style>
    <script>
        $(document).ready(function () {
            show_bucket();
        });
        function show_bucket(){
            $.ajax({
                type: "GET",
                url: "/bucket",
                data: {},
                success: function (response) {
                    let rows = response['buckets']
                    for (let i = 0; i < rows.length; i++) {
                        let bucket = rows[i]['bucket']
                        let num = rows[i]['num']
                        let done = rows[i]['done']

                        let temp_html = ``
                        if (done == 0) {
                            temp_html = `<li>
                                            <h2>✅ ${bucket}</h2>
                                            <button onclick="done_bucket(${num})" type="button" class="btn btn-outline-primary">완료!</button>
                                         </li>`
                        } else {
                            temp_html = `<li>
                                            <h2 class="done">✅ ${bucket}</h2>
                                         </li>`
                        }
                        $('#bucket-list').append(temp_html)
                    }
                }
            });
        }
        function save_bucket(){
            let bucket = $('#bucket').val()

            $.ajax({
                type: "POST",
                url: "/bucket",
                data: {bucket_give:bucket},
                success: function (response) {
                    alert(response["msg"])
                    window.location.reload()
                }
            });
        }
        function done_bucket(num){
            $.ajax({
                type: "POST",
                url: "/bucket/done",
                data: {num_give:num},
                success: function (response) {
                    alert(response["msg"])
                    window.location.reload()
                }
            });
        }
    </script>
</head>
<body>
    <div class="mypic">
        <h1>나의 버킷리스트</h1>
    </div>
    <div class="mybox">
        <div class="mybucket">
            <input id="bucket" class="form-control" type="text" placeholder="이루고 싶은 것을 입력하세요">
            <button onclick="save_bucket()" type="button" class="btn btn-outline-primary">기록하기</button>
        </div>
    </div>
    <div class="mybox" id="bucket-list">
    </div>
</body>
</html>

3. 웹 서비스 런칭(프로젝트 배포)

·

서버 컴퓨터를 클라우드에서 사용하기 위해 AWS 클라우드 서비스에서 EC2 사용권을 구입해서 사용


  - AWS EC2 구매 : OS - 리눅스 Ubuntu, 
  - EC2 콘솔 페이지 : https://ap-northeast-2.console.aws.amazon.com/ec2/v2/home?region=ap-northeast-2
  - Ubuntu Server 22.04버전 구매, Key Pair는 별도 저장

  - EC2 접속하기
   : gitbash 실행 후 아래 입력

ssh -i 받은키페어를끌어다놓기 ubuntu@AWS에적힌내아이피

 - EC2 셋팅하기
   : 아래 Code를 gitbash에서 순서대로 입력하여 셋팅하고
     FileZilla는 사이트관리자 열기 → 사이트 관리자에서 각각 세팅하고 '확인' 클릭하면 서버의 파일들을 볼 수 있음
     *Host : AWS상의 내 EC2서버의 ip // User : ubuntu

# python3 -> python
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10

# pip3 -> pip
sudo apt-get update
sudo apt-get install -y python3-pip
sudo update-alternatives --install /usr/bin/pip pip /usr/bin/pip3 1

# port forwarding (80포트로 들어오는 요청을 5000포트로 넘겨주는 명령어)
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 5000

 


 
 ※ SSH(Secure Shell Protocol) : 다른 컴퓨터에 접속할 때 쓰는 프로그램, 보안이 상대적으로 뛰어난 편
    접속할 컴퓨터의 22번 포트가 열려있어야 접속 가능.

  - 파이썬 파일로 실행

#python 실행
python test.py

#pip로 패키지 설치
pip install flask
pip ilnstall pymongo dnspython

#flask 서버 실행
python app.py

- AWS에서 5000포트를 열어주기 (인바운드 요청 포트 열기)
   EC2 관리 콘솔에서 아래와 같이 셋팅하기

 ※ http요청에서는 80포트가 기본(포트번호(~:80)를 입력하지 않아도 자동으로 접속된다.)
    포트번호를 입력하지 않아도 자동으로 접속되기 위해, 80포트로 오는 요청을 5000포트로 전달하게 하는 포트 포워딩(port forwarding) 사용

- nohup 설정
  1) SSH 접속을 끊어도 서버가 계속 돌게 하기

nohup python app.py &

  2) 서버 (강제) 종료하기

ps -ef | grep 'python app.py' | awk '{print $2}' | xargs kill

 - 도메인 연결하기(가비아, https://dns.gabia.com/)

4. og 태그

· og 태그 : 카톡에 전송시 보여지는 이미지, 제목, 내용 설정
  static 폴더에 사용할 이미지 파일 저장
  아래 코드 삽입 (위치 : HTML의 <head>~</head> 사이)
   

<meta property="og:title" content="내 사이트의 제목" />
<meta property="og:description" content="보고 있는 페이지의 내용 요약" />
<meta property="og:image" content="이미지URL" />


    

반응형

댓글