공부한 내용 정리하는 공간입니다.
틀린 내용이 있을 수 있습니다.
모든 지적, 첨언 환영합니다.
오늘의 코드
사용자에게도 번역된 파일 전달
이전 게시글에서 upload 라우터의 return부터 내용 변경
이전 내용은 동일함
2025.01.17 - [클라우드기반 스마트 융합보안 과정/Python] - [Python] request.files[ ], 시트.iter_rows()
@app.route("/upload", methods=['GET', 'POST'])
def upload():
file = request.files["file"]
file.save(os.path.join("uploads", file.filename))
workbook = openpyxl.load_workbook(os.path.join("uploads", file.filename))
sheet = workbook.active
for row in sheet.iter_rows():
for cell in row:
translated = GoogleTranslator(source='ko', target='en').translate(cell.value)
cell.value = translated
workbook.save('result_en.xlsx')
return render_template('result.html', file_name = file.filename)
@app.route("/download_report")
def download_report():
return send_file('result_en.xlsx', as_attachment=True)
if __name__ == '__main__':
app.run(debug=True)
rander_template('A.html', file_name = 파일이름)
파일이름을 변수 file_name에 담은 html 파일을 렌더링해서 웹 브라우저에 표시
템플릿 안의 {{ file_name }} 부분이 파일 이름으로 대체됨
send_file('파일이름', as_attachment=True)
서버에 저장된 파일을 클라이언트에게 전달하는 함수
파일 이름이나 절대 경로로 파일을 지정
as_attachment=True : 파일 다운로드 강제 진행
오늘의 코드
사용자에게도 번역된 파일 전달
이전 게시글에서 upload 라우터의 return부터 내용 변경
이전 내용은 동일함
2025.01.17 - [클라우드기반 스마트 융합보안 과정/Python] - [Python] request.files[ ], 시트.iter_rows()
@app.route("/upload", methods=['GET', 'POST'])
def upload():
file = request.files["file"]
file.save(os.path.join("uploads", file.filename))
workbook = openpyxl.load_workbook(os.path.join("uploads", file.filename))
sheet = workbook.active
for row in sheet.iter_rows():
for cell in row:
translated = GoogleTranslator(source='ko', target='en').translate(cell.value)
cell.value = translated
workbook.save('result_en.xlsx')
return render_template('result.html', file_name = file.filename)
@app.route("/download_report")
def download_report():
return send_file('result_en.xlsx', as_attachment=True)
if __name__ == '__main__':
app.run(debug=True)
오늘의 코드 설명
return render_template('result.html', file_name = file.filename)
result.html에 file.filename을 변수 file_name으로 전달
>file.filename=index.html의 <form>태그에서 가져온 데이터를 저장한 파일의 이름
return send_file('result_en.xlsx', as_attachment=True)
result_en.xlsx 파일을 웹 브라우저에 전송하고 사용자에게 다운로드 자동 진행