[Python] Flask 모음

Jen Y·2021년 7월 6일
0

Python

목록 보기
13/17

파일 업로드하기


# 엑셀 attach
from flask import send_file

@test.route('/test', methods=['POST'])
def test():
    file_path = os.path.join(os.getcwd(), "app", "test", "files")
    today = datetime.date.today().strftime('%y-%m-%d')
    file_name = f"test_{today}.xlsx"
    out_file = os.path.join(file_path, 'new', file_name)
    
    XLSX_MIMETYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

    return send_file(out_file,
    			as_attachment = True,
            		attachment_filename = file_name,
            		mimetype = XLSX_MIMETYPE)
axios({
    method: 'POST',
    url: '/api/test',
    data: { name: name },
    dataType: "json",
    responseType: "blob"
})
.then(function (response) {
    let xlsx_file = response.data;
    let blob = new Blob ([xlsx_file], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });
    let link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    const contentDisposition = response.headers['content-disposition'];
    let fileName = 'unknown';
    if (contentDisposition) {
        const [ fileNameMatch ] = contentDisposition.split(';').filter(str => str.includes('filename'));
    if (fileNameMatch)
        [ , fileName ] = fileNameMatch.split('=');
    }
    link.download =  fileName.replace(/"/g, "")
    link.click();
    link.remove();
})
.catch(function (error) {
    console.log(error);
});

Sqlalchemy

from sqlalchemy.sql import text

def patch(self, id):
    response_object = {'status': 'success'}
    parser.add_argument('name')
    args = parser.parse_args()

    name = args['name']
    
    data = db.session.query(text(name)).from_statement(text(f"SELECT {name} FROM TABLE WHERE id=:id")).params(id=id).first()
    d = [str(d) for d in data]
    
    if not(value):
      db.session.query(TABLE).filter(TABLE.id == id).update({name: None})
    else:
      db.session.query(TABLE).filter(TABLE.id == id).update({name: value})
    db.session.commit()
    

0개의 댓글