본문 바로가기

Data Science/3. 데이터 엔지니어링

[n334]Deployment

■ Key words

  ㆍHeroku

  ㆍ배포

  ㆍWSGI(Web Server Gateway Interface)

  ㆍ환경변수

 

■ 주요내용

  ㆍHeroku 배포

     - WSGI : 웹서버와 웹 app.의 인터페이스를 위한 python의 framework. 다리 역할을 맡는 middleware.

                 WSGI가 서버는 아니지만, 개발단계에서 test 할 수 있도록 일부 서버 기능을 포함함;gunicorn

       · gunicorn(green unicorn) : python의 WSGI HTTP Server. UNIX 체계에서 HTTP 요청을 처리함.

     - Heroku : 클라우드 플랫폼 서비스(Platform-as-a-service). 코드를 배포할 서버에 올리고 URL을 쉽게 얻을 수 있음.

       ⇒ AWS의 EC2를 기반으로 app. 배포.

       * CLI 제공으로 터미널에서 작업 진행 가능 / git을 사용하여 repository 단위로 배포 및 관리 가능

       · Heroku CLI : 로그인 / Heroku apps 목록 확인 / app. 만들기 / 배포 및 확인

     - Heroku 배포 application 설정

       · Heroku와 python : heroku의 언어가 설정되어 있지 않기 때문에 서버에 등록된 코드 실행 시 에러 발생

         ⇒ requirements.txt / Pipfile / setup.py 중 하나로 언어 등 환경 지정 필요

       · Procfile(Process file) 설정하기 : 배포 링크에서 실행돼야 할 web application 지정 / WSGI 서버는 gunicorn

       · Heroku 서버에 로그인 : 설정된 현황 확인하기

  ㆍHeroku Database

     - Heroku add-ons : DB, 모니터링 및 분석 등 app을 지원하는 component 제공(postgresql 등)

       · Database add-on : Heroku dashboard / CLI를 통한 설치로 postgresql 등 부가기능 사용 가능

       · Database 초기 설정 : Heroku와 연결된 add-ons / 환경변수 확인 및 수정 가능(DATABASE_URL)

  ㆍ환경변수 : 개발하고 있는 local에서만 접근 가능한 정보 / export/os를 활용하여 변수 지정/접근 가능

     - dotnv 패키지 : 환경변수 관리를 수월하도록 도와주는 패키지

     - Heroku 환경변수 관리 : add-on으로 DB 추가 시 연결된 앱에 DATABASE_URL이라는 환경변수 자동 생성

       · 환경분리 : test 과정 중에서 활용한 비밀번호, API 키 등을 배포되지 않도록 별도로 환경변수 설정

         ⇒ error/bug 등 실제 배포 단계에 영향을 안 미치고, local과 독립적으로 관리할 수 있음

 

■ Session note

ㅁ 오전 session
  ㆍpython 3.8.11. : major version - 8. / minor viersion - 11. => Heroku는 이미 python이 설치되어 있고(가상환경처럼 python을 설치하는 것이 아니고), major version만 맞으면 구동에 문제는 없을 것
  ㆍPart_3/Part_1.py 파일의 data를 json= 으로 수정하기
  ㆍapp이 있는 폴더에서 'heroku logs'에서 에러 내역 확인하기
     - requirements.txt에서 pytest plugin 삭제하고 다시 시도해보기; 배포에 필요 없음
  ㆍembedding을 통해 text로 바꾸기 위해; 컴퓨터가 문자를 분석할 수 없으므로 벡토를 통해 숫자로 표현; 모델 학습
  ㆍos.remove가 permission error를 돌려주는 이유 : windows에서는 os.replace 사용 권장
     - os.rename(CSV_FILEPATH, TEST_CSV_PATH)
  ㆍtwit_app/utils/main_funcs.py 43번째 줄 user_1, user_2; 수강생이 만드는 user.py와 연결됨
     - user와 twits를 연결하여 user1, 2 중 누가 더 많은지 확인하는 목적
  ㆍflask_sqlalchemy에 Column 함수 등이 내장되어 있어 from sqlalchemy import Column 등을 할 필요 없음
  ㆍUser를 대문자로 넣는 이유 : class이기 때문에
  ㆍBLOB : db.pickle type; json(dictionary 아님)과 같은 하나의 증명화 방법; pickle도 dictionary가 아니어서 python에서 바로 읽을 수는 없음.
     * 이진(binary) 필드로 저장 : 0과 1로 표현된 필드로  저장
     - python에서 json으로 저장하기 : dump / load로 json 형태로 저장
     - python에서 pickle(pkl)로 저장하기 : 사람은 이해할 수 없고, 컴퓨터만 이해할 수 있는 형식으로 저장; python에 특화된 형식으로 저장
     * pickle file을 사용하는 이유 : python에서 특정 object를 저장할 때 boolean, int, float, complex number, str, tuple, list, set, dictionary 등의 형식을 저장하여 다른 곳에서도 호환이 가능 하게끔 해줌
  ㆍtwit_app/services/tweepy_api.py에 있는 api_key 등은 개인 키 사용
  ㆍadd_user() : urclass 기준으로 작성
     - json으로 데이터 받아오기 : username = request.get_json('username')
     - username이 없는 경우 : if not username: return "Needs username", 400
     - twitter에서 없는 경우 : if not tweepy_api.get_user(username): return redirect(url_for('main.user_index', msg_code=1), code=400)
   * msg_code=1 : user does not exist
     - find_user = user_model.User.query.filter_by(username=username).first() # first()를 안 쓰면 list를 받아옴
     - find_user가 존재하는 경우, twit update 필요 : if find_user: tweets = tweepy_api.get_tweets(username)
       · 만약 DB에 해당 tw.id가 존재한다면 넘어가고, 없으면 추가 : for tw in tweets: if not tweet_model.Tweet.query.filter_by(id=tw.id).first(): new_tweet = tweet_model.Tweet(id=tw.id=tw.text, text, embedding=embedding_api, user_id=find_user.id)
          # embedding, db 적당히 가져오기
     - return redirect(url_for('main.user_index', msg_code=1), code=200)

ㅁ 오후 session
  ㆍ환경변수 예시 : Heruko URL - username/pw/server:port/경로(DB)
     - 개인정보 유출의 위험이 있으므로, 최대한 숨기는 것이 좋음
  ㆍHeroku App name : 임의으로 지어도 되지만, 이미 있는 것은 안 됨(id와 같은 맥락)
  ㆍbootstrap 사용 시 <head>부분에 CSS와 javascript를 설치해야 함
  ㆍ주소는 환경변수에 저장되어 있기 때문에 "DATABASE_URL"을 통해 환경변수만 불러오면 됨
  ㆍtable 만들기 : elephantDB에 들어가서 직접 만들기 / CLI에서 만들기
    * SQLite에서 id column 만들기 : integer 또는 serial(자동 오름차순 입력)로 지정 가능
  ㆍpostgres 사용 시 postgresql+psycopg2인 거 잊지 말기 // 가상환경에 설치하는 것도 잊지 말기

 

■ 주요함수

  ㆍgunicorn

# 설치
pip install gunicorn

# 실행
gunicorn [옵션] [WSGI 어플리케이션]

# application factory 실행
gunicorn --workers=1 'flask_app:create_app()' # woker 갯수 지정 가능

# gunicorn은 파일이나 모듈 내에서 바로 접근이 가능하기 때문에 별도로 create_app으로 별도 app 객체를 생성하지 않는다.
gunicorn --workers=4 flask_app:app

  ㆍHeroku

# 로그인; 설치는 홈페이지에서 진행 / 계정 먼저 만들기
heroku login

# 계정 내 등록된 app 목록 확인
heroku apps

# local에서 개발한 app 등록을 위한 app 만들기 / app_name은 기존에 등록된 것과 중복 불가
heroku create [app_name]

# github에 repository 추가
git remote -v 'heroku 주소'

# git push 후 배포용 주소 얻기
git push heroku master

# pip에 설치된 파일들 requirements.txt로 저장하여 내보내기
pip freeze > requirements.txt

# gunicorn을 서버로 웹에서 실행해야 할 process 지정
web: gunicorn --workers=2 'flask_app:create_app()'

# 생성한 Heroku app의 파일 시스템에 접근
heroku run bash

  ㆍHeroku Add-on

# CLI에서 postgresql 설치; hobby-dev는 무료 plan / [app_name]에 사용자가 이름 지정 가능
heroku addons:create heroku-postgresql:hobby-dev --main [app_name]

# heroku에 설치된 add-on list 확인
heroku addons --app [app_name]

# 설치된 heroku의 환경변수 확인
heroku config --app [app_name]

  ㆍ환경변수

# 환경변수 확인
env

# 새로운 환경변수 지정
export [변수명]=[변수값]

# 변수에 접근 : os / 예시
export ENV_PRAC="hello world"

import os
print(os.environ["ENV_PRAC"])

# dotenv(.env) 패키지 활용
pip install python-dotenv

# .env 파일
export env_1 = 'hello world'
export env_2 = 'bye bye'
export env_3 = 42

# env_prac.py
import os
from dotenv import load_dotenv
load_dotenv()

print(os.getenv('env_1'))
print(os.getenv('env_2'))
print(os.getenv('env_3'))
# 일반적으로 .env 파일은 .gitignore를 이용하여 무시하도록 설정함


# Heroku 환경변수 관리 : 자동으로 DATABASE_URL이라는 환경변수 생성 / heroku config로 관리
heroku config:set [변수명]=[변수값]

 

■ Reference

  ㆍWSGO : https://ko.wikipedia.org/wiki/%EC%9B%B9_%EC%84%9C%EB%B2%84_%EA%B2%8C%EC%9D%B4%ED%8A%B8%EC%9B%A8%EC%9D%B4_%EC%9D%B8%ED%84%B0%ED%8E%98%EC%9D%B4%EC%8A%A4

 

웹 서버 게이트웨이 인터페이스 - 위키백과, 우리 모두의 백과사전

웹 서버 게이트웨이 인터페이스(WSGI, Web Server Gateway Interface)는 웹서버와 웹 애플리케이션의 인터페이스를 위한 파이썬 프레임워크다. WSGI는 처음에 2003년 PEP-333으로 규정되었다.[1]. 2010년에 출판

ko.wikipedia.org

  ㆍgunicorn : https://gunicorn.org/

 

Gunicorn - Python WSGI HTTP Server for UNIX

Deployment Gunicorn is a WSGI HTTP server. It is best to use Gunicorn behind an HTTP proxy server. We strongly advise you to use nginx. Here's an example to help you get started with using nginx: server { listen 80; server_name example.org; access_log /var

gunicorn.org

  ㆍHeroku : https://dashboard.heroku.com/apps

 

Heroku

 

dashboard.heroku.com

  ㆍHeroku Procfile : https://devcenter.heroku.com/articles/getting-started-with-python#define-a-procfile

 

Getting Started on Heroku with Python | Heroku Dev Center

This tutorial will have you deploying a Python app (a simple Django app) in minutes. Hang on for a few more minutes to learn how it all works, so you can make the most out of Heroku. The Heroku CLI requires Git, the popular version control system. If you d

devcenter.heroku.com

  ㆍHeroku 환경변수 : https://devcenter.heroku.com/articles/getting-started-with-python#define-config-vars

 

Getting Started on Heroku with Python | Heroku Dev Center

This tutorial will have you deploying a Python app (a simple Django app) in minutes. Hang on for a few more minutes to learn how it all works, so you can make the most out of Heroku. The Heroku CLI requires Git, the popular version control system. If you d

devcenter.heroku.com

  ㆍHeroku CLI : https://devcenter.heroku.com/categories/command-line

 

Command Line | Heroku Dev Center

 

devcenter.heroku.com

  ㆍWerkzeug : https://werkzeug.palletsprojects.com/en/2.0.x/

 

Werkzeug — Werkzeug Documentation (2.0.x)

 

werkzeug.palletsprojects.com

 

'Data Science > 3. 데이터 엔지니어링' 카테고리의 다른 글

[n333]Flask(2/2)  (0) 2021.07.26
[n332]Flask(1/2)  (0) 2021.07.23
[n331]Intro to API(Application Programming Interface)  (0) 2021.07.22
[n324]ORM(Object Relational Mapping)  (0) 2021.07.20
[n323]Web Scraping  (0) 2021.07.19