Python flask

test edit : db 데이터 수정 이후, 실행 결과를 리턴

test list : db의 table 조회 이후, 여러 행을 리스트 형태로 리턴

test detail : db 데이터 조회 결과가 1건인 경우, json 형태로 리턴

from flask import render_template, request, flash, redirect, url_for, Blueprint, Markup, jsonify, session, make_response
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text, update
from sqlalchemy.exc import SQLAlchemyError

@bts_blueprint.route('test/edit', methods=['POST'])
def test_edit():

    print("## test_edit ##")

    try:
        # 처리 변수
        numId = request.form['id']
        strName = request.form['name']

        # 처리 로직
        sql = text('update tblTest set name = :strName where id = :numId')
        connection = db.session.connection()
        db.engine.execute(sql, numId=numId, strName=strName)
                
        return jsonify(message="Edit Success"), 200

    except (RuntimeError, TypeError, NameError, SQLAlchemyError) as e:
        print("#### Edit Failed !! " + str(e))
        db.session.rollback()

        return jsonify(message=str(e)), 1000
        
        
@bts_blueprint.route('test/list', methods=['POST'])
def test_list():

    print("## test_list ##")

    # 처리 변수
    numId = request.form['id']

    # 처리 로직
    sql = text('select a, b, c, d, e from tblTest where id > :numId')
    connection = db.session.connection()
    results = db.engine.execute(sql, numId=numId)
                
    return render_template('test.html', results=list(results))


@bts_blueprint.route('test/detail', methods=['POST'])
def test_detail():

    print("## test_detail ##")

    # 처리 변수
    numId = request.form['id']

    # 처리 로직
    sql = text('select a, b, c from tblTest where id = :numId')
    connection = db.session.connection()
    results = db.engine.execute(sql, numId=numId)

    if results != None:
        results_detail = {}
        for r in results:
            results_detail['a'] = r[0]
            results_detail['b'] = r[1]
            results_detail['c'] = r[2]
            
    return jsonify(results_detail=results_detail)

javascript

funtion test_edit()
{
    // Test edit
    $.ajax({
        url:'/test/edit',
        type:'POST',
        data: {id:id, name:name},
        success: function(data){
            //Success
            showAlert('Edit Successful!!!', '', 2, 2000);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            var err_msg = JSON.parse(xhr.responseText);

            if (thrownError == 'UNKNOWN'){
                fail_msg = err_msg.message + ' (' + xhr.status + ')'
            } else {
                fail_msg = err_msg.message + ' (' + thrownError + ',' + xhr.status + ')';
            }
            showAlert('Edit Fail...','', 4, 3000);
        }
    });
}


funtion test_list()
{
    // Test list
    $.ajax({
        url:'/test/list',
        type:'POST',
        data: {id:id},
        success: function(data){
            //Success
            for(var key in data){
                console.log(key, data[key]);
            }
            
            showAlert('detail Successful!!!', '', 2, 2000);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            var err_msg = JSON.parse(xhr.responseText);

            if (thrownError == 'UNKNOWN'){
                fail_msg = err_msg.message + ' (' + xhr.status + ')'
            } else {
                fail_msg = err_msg.message + ' (' + thrownError + ',' + xhr.status + ')';
            }
            showAlert('list Fail...','', 4, 3000);
        }
    });
}


funtion test_detail()
{
    // Test detail
    $.ajax({
        url:'/test/detail',
        type:'POST',
        data: {id:id},
        success: function(data){
            //Success
            detail_a = data.results_detail.a
            detail_b = data.results_detail.b
            detail_c = data.results_detail.c
            
            showAlert('detail Successful!!!', '', 2, 2000);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            var err_msg = JSON.parse(xhr.responseText);

            if (thrownError == 'UNKNOWN'){
                fail_msg = err_msg.message + ' (' + xhr.status + ')'
            } else {
                fail_msg = err_msg.message + ' (' + thrownError + ',' + xhr.status + ')';
            }
            showAlert('detail Fail...','', 4, 3000);
        }
    });
}

to Top