Background Image
조회 수 2909 추천 수 1 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

Python 기반 Web Framework를 떠올리면 DJango를 떠올릴텐데요.

Django 보다 가볍고 쉬운 Flask Web Framework와 CUBRID 데이터 베이스 연동 하는 방법을 기술 하였습니다.

- Windows 환경에서의 구성과 Linux 환경에서의 구성


Spec.


CUBRID 10.2 64bit


Windows 10 64 bit

- python 3.6.7

- Flask 1.1.2

- Werkzeug 1.0.1


Ubuntu 20.04.1 LTS (Linux)

- python 3.8.2

- Flask 1.1.2

- Werkzeug 1.0.1


스크린샷 2020-08-12 오후 2.47.15.png



CUBRID Server


# vi /etc/hosts
- hostname과 IP 매칭

# ufw allow 33000/tcp

# su - cubrid
$ wget http://ftp.cubrid.org/CUBRID_Engine/10.2_latest/CUBRID-10.2-latest-Linux.x86_64.sh

$ sh CUBRID-10.2-latest-Linux.x86_64.sh

$ cubrid service start

$ cubrid server start demodb


Windows (Flask) WEB Server


Python Install

python : https://www.python.org/

- 3.6.7  Release version 다운로드 및 설치

- 환경 변수

Path : C:\Users\<username>\AppData\Local\Programs\Python\Python36\Scripts 추가

Path : C:\Users\<username>\AppData\Local\Programs\Python\Python36 추가

flask Install
cmd> pip3 install flask

cmd> flask --version


CUBRID Driver

- CUBRID FTP : http://ftp.cubrid.org/CUBRID_Drivers/Python_Driver/10.2.0/Windows/CUBRID-10.2-latest-windows-python36-amd64.zip

- zip 압축 해제 : RB-10.2 폴더의 3개 파일 확인

- C:\Users\<username>\AppData\Local\Programs\Python\Python36\Lib 경로로 이동

- 주의 사항 : _cubrid.cp-win_amd64.pyd 파일 이름 변경 _cubrid.cp36-win_adm64.pyd 변경 해서 옮겨야 인식함.

- 드라이버 Python 라이브러리 경로로 이동 완료

cmd> python
>>> import CUBRIDdb

- import 수행 시 오류가 없으면 정상

캡처.PNG



Ubuntu (Flask) WEB Server


Python Install

python  : https://www.python.org/

- 설치 python 버전 확인 3.8.2 버전이 아니더라도 가능

- 원하는 버전은 python 홈페이지에서 다운로드 진행 및 설치


flask Install

$ sudo apt-get install python3-flask
$ pip3 install flask

$ flask --version


CUBRID Driver 빌드
- Windwos 버전과 달리 Linux 버전은 드라이버 소스 빌드 필요.

$ wget http://ftp.cubrid.org/CUBRID_Drivers/Python_Driver/10.2.0/Linux/cubrid-python-10.2-latest.tar.gz

$ tar -xvzf cubrid-python-10.2-latest.tar.gz 

$ cd RB-10.2.0

- 주의 사항 : 빌드 전, regex38a.h 헤더 파일 다른 디렉토리 복사 필요.
$ cp ./RB-10.2.0/cci-src/external/libregex38a/include/regex38a.h ./RB-10.2.0/cci-src/include/

$ sudo apt-get install libncurses5

- ncurses5 필수 라이브러리 설치 필요 (kernel 버전업이 되면서 최신 버전에서는 ncurses6버전을 사용하고 있음, CUBRID는 ncurses5버전 사용)

$ cd RB-10.2.0

$ python setup.py install

- 빌드 진행 후 기타 라이브러리 에러가 발생하면, 해당 라이브러리 설치 필요.

$ python

>>> import CUBRIDdb

- import 수행 시 오류가 없으면 정상 


Source 작성


스크린샷, 2020-08-12 23-14-48.png


- 테스트를 위하여 위와 같은 레이아웃을 이용하여 진행

run.py

# ./flask/run.py : flask 구동을 위한 코드
from app import app
app.run(host='localhost', port=8080)

__init__.py

# ./flask/app/__init__.py : flask에 의해 구동 되고 제일 먼저 수행 되는 python 코드

from flask import Flask

app = Flask(__name__)

from app.main.test import test as main

app.register_blueprint(main)

test.py

# ./flask/app/main/test.py : flask를 활용한 URL별 라우팅 동작

from flask import Blueprint, request, render_template, flash, redirect, url_for
from flask import current_app as current_app
from app.module import cubrid_test


test = Blueprint('main', __name__, url_prefix='/main')


@test.route('/', methods=['GET'])
def index():
    return render_template('/main/index.html',
                            result=None,
                            resultData=None,
                            resultUPDATE=None)


@test.route('/insert', methods=['GET'])
def insert():
    db_class = cubrid_test.cubrid_test()
    sql      = "INSERT INTO flask_test_tbl(content) VALUES('flask_test')"
    db_class.execute(sql)
    db_class.commit()

    db_class.close()

    return render_template('/main/index.html',
                           result='INSERT is done!')


@test.route('/select', methods=['GET'])
def select():
    db_class = cubrid_test.cubrid_test()
    sql      = "SELECT idx content \
                FROM flask_test_tbl"
    db_class.execute(sql)
    db_class.commit()

    db_class.close()

    return render_template('/main/index.html',
                            result='SELECT is done!')


@test.route('/update', methods=['GET'])
def update():
    db_class = cubrid_test.cubrid_test()
    sql      = "UPDATE flask_test_tbl SET content='done'  WHERE content='flask_test'"
    db_class.execute(sql)
    db_class.commit()

    db_class.close()

    return render_template('/main/index.html',
                            result='UPDATE is done!')

index.html

<!-- ./flask/app/templates/main/index.html : 메인 페이지 -->

<!DOCTYPE html>
<html lang="en">
    <head>
        CUBRID Flask Connection test. <br><br>
    </head>
    <body>
        <input type="button" value="INSERT" onclick="location.href='/main/insert'"><br><br>
        <input type="button" value="SELECT" onclick="location.href='/main/select'"><br><br>
        <input type="button" value="UPDATE" onclick="location.href='/main/update'"><br><br>
    <br><br><br>
    <div>
        SQL RUN Check : {{result}}
    </div>
    </body>
</html>

Database schema

# csql을 활용하여, 테스트를 위한 스키마를 미리 생성


CREATE TABLE flask_test_tbl(

    idx int auto_increment NOT NULL PRIMARY KEY,

    content varchar NOT NULL

) REUSE_OID;


cubrid_test.py

# ./flask/app/module/cubrid_test.py : CUBRID 데이터 베이스 접속 및 수행할 메서드 python 코드


import CUBRIDdb

  

class cubrid_test():

    def __init__(self):

        self.db = CUBRIDdb.connect('CUBRID:<DB IP>:33000:demodb:::','public','')

        self.cursor = self.db.cursor()


    def execute(self, query):

        self.cursor.execute(query)


    def commit(self):

        self.db.commit()


    def close(self):
        self.cursor.close()
        self.db.close()


Flask Start


Windows와 Ubuntu 모두 동일

$ cd ./flask

$ python run.py 

- 테스트를 위하여, 포그라운드로 동작


user1@hostname1:~/flask$ python ./run.py 

 * Serving Flask app "app" (lazy loading)

 * Environment: production

   WARNING: This is a development server. Do not use it in a production deployment.

   Use a production WSGI server instead.

 * Debug mode: off

 * Running on http://localhost:8080/ (Press CTRL+C to quit)




WEB Browser 확인


접속 URL http://localhost:8080/main/


스크린샷, 2020-08-12 22-59-31.png


스크린샷, 2020-08-12 22-59-43.png


스크린샷, 2020-08-12 22-59-50.png


스크린샷, 2020-08-12 22-59-57.png


스크린샷, 2020-08-12 23-24-04.png

- CUBRID 엔진에서 로그 확인 시 정상적으로 SQL 처리가 되는 것을 확인 할 수 있습니다.

- sql log 경로 : $CUBRID/log/broker/sql_log/


마치며.


- Django처럼 불필요한 라이브러리 없이 부트스트랩과 MDB를 활용하여 멋진  UI를 만들고 CUBRID 데이터 베이스를 활용하여, 좋은 웹 애플리케이션을 만들 수 있으면 좋겠습니다.

- 추가적으로 CUBRID import 과정에서 오류가 발생한다면 댓글 부탁 드립니다.

- 감사합니다.


Contact Cubrid

대표전화 070-4077-2110 / 기술문의 070-4077-2113 / 영업문의 070-4077-2112 / Email. contact_at_cubrid.com
Contact Sales