[Python] request.files[ ], 시트.iter_rows()

공부한 내용 정리하는 공간입니다.

틀린 내용이 있을 수 있습니다.

모든 지적, 첨언 환영합니다.

오늘의 코드

1. 사용자가 업로드한 파일 저장

2. 파일 번역해서 새로운 파일로 저장

from flask import Flask, render_template, request
from deep_translator import GoogleTranslator
import os
import openpyxl

app = Flask(__name__)

@app.route("/")
def index():
    return render_template('index.html')

@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')

if __name__ == '__main__':
    app.run(debug=True)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>번역할 파일 업로드</title>
</head>
<body>
    <h1>자동번역서비스</h1>
    <form method="post" action="{{url_for('upload')}}" enctype="multipart/form-data">
        <b>번역할 파일을 업로드 하세요</b></br>
        <input type="file" name="file">
        <input type="submit" value="업로드">
    </form>
</body>
</html>

result.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>upload result</title>
</head>
<body>
   <h1>업로드 완료! 번역 결과는 result_en.xlsx 파일 확인하기!</h1> 
</body>
</html>

 


request.files[ ]

클라이언트로부터 제출된 HTML 폼 데이터를 가져올 때 사용

폼 태그에서 enctype="multipart/form-data 속성을 설정하고 input type="file" 태그로 파일 선택해서 가져옴

폼 필드의 이름에 매핑된 값을 반환

request.['필드이름'] 형식으로 사용

 


시트.iter_rows()

엑셀 시트에서 행(row)을 반복(iterate)할 때 사용

각 행을 반복하여 처리할 수 있음

각 행에 대한 정보를 튜플 형태로 반환

튜플 안에는 각 셀의 값이 들어있음

 


오늘의 코드

1. 사용자가 업로드한 파일 저장

2. 파일 번역해서 새로운 파일로 저장

from flask import Flask, render_template, request
from deep_translator import GoogleTranslator
import os
import openpyxl

app = Flask(__name__)

@app.route("/")
def index():
    return render_template('index.html')

@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')

if __name__ == '__main__':
    app.run(debug=True)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>번역할 파일 업로드</title>
</head>
<body>
    <h1>자동번역서비스</h1>
    <form method="post" action="{{url_for('upload')}}" enctype="multipart/form-data">
        <b>번역할 파일을 업로드 하세요</b></br>
        <input type="file" name="file">
        <input type="submit" value="업로드">
    </form>
</body>
</html>

result.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>upload result</title>
</head>
<body>
   <h1>업로드 완료! 번역 결과는 result_en.xlsx 파일 확인하기!</h1> 
</body>
</html>

오늘의 코드 설명

file = request.files["file"]

본문에 포함된 name 속성이 file인 form 데이터를 가져와서 file에 저장

    >name 속성이 file인 form은 index.html에 있는 <input> 태그

    >index.html의 <form> 태그는 서버에 있는 이름이 upload인 라우터에 POST 요청을 보냄

file.save(os.path.join("uploads", file.filename))

디렉터리 uploads와 file.filename으로 경로를 만들어서 이 경로에 저장

    >uploads 안에 업로드한 파일 이름으로 파일 저장

workbook = openpyxl.load_workbook(os.path.join("uploads", file.filename))

디렉터리 uploads와 file.filename으로 경로를 만들어서 이 경로에 있는 엑셀 파일 열고 workbook에 저장

    >사용자로부터 업로드되어 저장된 파일을 열기

for row in sheet.iter_rows():

row는 활성화된 시트의 행 단위로 반복

translated = GoogleTranslator(source='ko', target='en').translate(cell.value)

cell 값(텍스트)를 한국어에서 영어로 번역해서 translated에 저장

cell.value = translated

cell 값을 번역된 translated로 변경

workbook.save('result_en.xlsx')

번역 작업이 끝난 워크북을 'result_en.xlsx'로 저장

return render_template('result.html')

저장을 완료한 뒤 'result.html'을 렌더링하여 반환

브라우저에 result.html 내용 표시

index.html

<form method="post" action="{{url_for('upload')}}" enctype="multipart/form-data">
	<b>번역할 파일을 업로드 하세요</b></br>
	<input type="file" name="file">
	<input type="submit" value="업로드">
</form>

<form> : 데이터를 입력받아 서버로 전송하기 위한 태그

method="post" : 데이터를 POST 방식으로 서버에 전송

action="{{url_for('upload')}}" : 서버에서 upload라는 이름의 라우터에 요청을 보냄

    > type="submit" 으로 전송된 내용을 서버의 upload라우터로 전송

enctype="multipart/form-data" : 파일을 서버로 전송할 때 필수로 포함

input type="file" : 파일을 입력받는 필드

input type="submit" : 버튼 클릭 시 폼 데이터를 action 경로로 전송

    >action을 통해 서버의 라우터 upload로 데이터 전송

    ><button type="submit">업로드</button> 과 동일