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

올해 01월 01일, 올해 12월 마지막일

//현재 시간
> var Nowdate = new Date()
> Nowdate 
Tue Jul 06 2021 23:36:20 GMT+0900 (한국 표준시)
//현재 년도
> FullYear = Nowdate.getFullYear()
2021
//현재 달
> Tmp_Month = Nowdate.getMonth()+1
7
> CurrentMonth = Tmp_Month >= 10 ? Tmp_Month : '0' + Tmp_Month
"07"
//마지막 달의 마지막 일
> (new Date(FullYear, 12, 0))
Fri Dec 31 2021 00:00:00 GMT+0900 (한국 표준시)
> (new Date(FullYear, 12, 0)).getDate()
31
// 올해 01월 01일
> FullYear + '-01-01 00:00:00'
"2021-01-01 00:00:00"
// 올해 12월 마지막일
> FullYear + '-12-' + LastDay + ' 23:59:59'
"2021-12-31 23:59:59"

일주일전

> var Nowdate = new Date()
> Nowdate
Tue Jul 06 2021 23:55:01 GMT+0900 (한국 표준시)
> var Agodate = new Date(Nowdate.getTime() - (7*24*60*60*1000))
//일주일전
> Agodate 
Tue Jun 29 2021 23:55:01 GMT+0900 (한국 표준시)

//현재 달
> var NowMonth = ((Nowdate.getMonth()+1) >= 10 ? (Nowdate.getMonth()+1) : '0' + (Nowdate.getMonth()+1))
"07"
//현재 일
> var NowDay = (Nowdate.getDate() >= 10 ? Nowdate.getDate() : '0' + Nowdate.getDate())
"06"
// 일주일전 달
> var AgoMonth = ((Agodate.getMonth()+1) >= 10 ? (Agodate.getMonth()+1) : '0' + (Agodate.getMonth()+1))
"06"
// 일주일전 일
> var AgoDay = (Agodate.getDate() >= 10 ? Agodate.getDate() : '0' + Agodate.getDate())
29

//현재 날짜
> Nowdate.getFullYear() + '-' + NowMonth + '-' + NowDay + ' 00:00:00'
"2021-07-06 00:00:00"

//일주일전 날짜
> Agodate.getFullYear() + '-' + AgoMonth + '-' + AgoDay + ' 00:00:00'
"2021-06-29 00:00:00"

1일 추가, 1시간 추가

//1일 추가
> tmpdate = new Date(2021,07,07)
Sat Aug 07 2021 00:00:00 GMT+0900 (한국 표준시)
> tmpdate.setTime(tmpdate.getTime() + (24*60*60*1000))
1628348400000
> new Date(tmpdate)
Sun Aug 08 2021 00:00:00 GMT+0900 (한국 표준시)

//1시간 추가
> tmpdate = new Date(2021,07,07)
Sat Aug 07 2021 00:00:00 GMT+0900 (한국 표준시)
> tmpdate.setTime(tmpdate.getTime() + (1*60*60*1000))
1628265600000
> new Date(tmpdate)
Sat Aug 07 2021 01:00:00 GMT+0900 (한국 표준시)

포멧 변경

function sDateToDate(strDate)
{
    //Ex) '04/26/2021 4:37 PM'
    var yyyyMMDD = String(strDate)
    var sYear = yyyyMMDD.substring(6,10);
    var sMonth = yyyyMMDD.substring(0,2);
    var sDate = yyyyMMDD.substring(3,5);
    var sTime = yyyyMMDD.substring(10,19);

    //Ex) '2021-04-26 4:37 PM'
    return sYear + '-' + sMonth + '-' + sDate + sTime
}

기능

- yyyy-mm-dd HH:mm:ss 형태로 날짜 데이터 입/출력

- python flask에서 get, post 형태로 날짜 데이터 처리

 

js

<!-- jQuery -->
<script src="/ path /plugins/jquery/jquery.min.js"></script>
<!-- Select2 -->
<script src="/ path /plugins/select2/js/select2.full.min.js"></script>
<!-- InputMask -->
<script src="/ path /plugins/moment/moment.min.js"></script>
<!-- Tempusdominus Bootstrap 4 -->
<script src="/ path /plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js"></script>

css

<!-- Font Awesome -->
<link rel="stylesheet" href="/ path /plugins/fontawesome-free/css/all.min.css">
  
<!-- Select2 -->
<link rel="stylesheet" href="/ path /plugins/select2/css/select2.min.css">
<link rel="stylesheet" href="/ path /plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css">
  
<!-- Tempusdominus Bootstrap 4 -->
<link rel="stylesheet" href="/ Path /plugins/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css">

html

datetimepicker ID : search_start_time, search_end_time

datetime text ID : search_start_input, search_end_input

 

<!-- Start Time -->
<div class="form-group col-md-4">
  <div class="input-group">
	<div class="input-group date" id="search_start_time" data-target-input="nearest">
	  <span class="btn btn-warning iw-100">Start Time</span>
	  <input type="text" data-date-format='yyyy-mm-dd' class="form-control datetimepicker-input" id="search_start_input" name="search_start_input" data-target="#search_start_time"/>
	  <div class="input-group-append" data-target="#search_start_time" data-toggle="datetimepicker">
		  <div class="input-group-text"><i class="fa fa-calendar"></i></div>
		</div>
	</div>
  </div>
</div>

<!-- End Time -->
<div class="form-group col-md-4">
  <div class="input-group">
	<div class="input-group date" id="search_end_time" data-target-input="nearest">
	  <span class="btn btn-warning iw-100">End Time</span>
	  <input type="text" data-date-format='yyyy-mm-dd' class="form-control datetimepicker-input" id="search_end_input" name="search_end_input" data-target="#search_end_time"/>
	  <div class="input-group-append" data-target="#search_end_time" data-toggle="datetimepicker">
		  <div class="input-group-text"><i class="fa fa-calendar"></i></div>
		</div>
	</div>
  </div>
</div>

javascript

datetimepicker ID에 icon 및 format 적용

<script type="text/javascript">
    $(function () {
    
        //값 확인
        start_time = $('#search_start_input').val();
        end_time = $('#search_end_input').val();
    
        //Date and time picker
        $('#search_start_time').datetimepicker({ icons: { time: 'far fa-clock' }, format: 'yyyy-MM-DD HH:mm:ss' });
        $('#search_end_time').datetimepicker({ icons: { time: 'far fa-clock' }, format: 'yyyy-MM-DD HH:mm:ss' });
    });
</script>

python flask

datetime text ID로 값을 조회

#get 방식
@bts_blueprint.route('search/datetime_ex', methods=['GET'])
@login_required
def search_datetime_ex(name=''):
    
    #get 방식
    search_start_time = request.args.get('search_start_input')
    search_end_time = request.args.get('search_end_input')

    # 처리 로직
    var results = 0

    return results

#post 방식
@bts_blueprint.route('search/datetime_ex', methods=['POST'])
@login_required
def search_datetime_ex(name=''):

    search_start_time = request.form['search_start_input']
    search_end_time = request.form['search_end_input']
    
    # 처리 로직
    var results = 0
    
    return results

to Top