0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

こちらのシステムのユーザーインターフェースを改善して、アップロードした CSV ファイルの名前を表示するようにしました。
適合確認システム: モックアップの作成 (その2)

ChatGPT への依頼

最後にアップロードされたCSVファイルの名前も表示して下さい。

ChatGPT の回答

フォルダー構造

$ tree
.
├── app.py
└── templates
    └── index.html
app.py
from flask import Flask, request, render_template, session
import csv
from io import TextIOWrapper

app = Flask(__name__)
app.secret_key = 'your_secret_key_here'  # セッションを使用するための秘密鍵

# ホームページの表示
@app.route('/')
def index():
    result = session.pop('result', None) if 'result' in session else None
    filename = session.pop('filename', None) if 'filename' in session else None
    return render_template('index.html', result=result, filename=filename)

# ファイルのアップロードと処理
@app.route('/upload', methods=['POST'])
def upload():
    if 'csvfile' not in request.files:
        return "ファイルがありません"

    csvfile = request.files['csvfile']
    if csvfile.filename == '':
        return "ファイルがありません"

    # CSVファイルを読み込み、列数と行数を取得
    try:
        csv_reader = csv.reader(TextIOWrapper(csvfile, 'utf-8'))
        header = next(csv_reader)  # ヘッダーを読み飛ばす
        num_columns = len(header)
        num_rows = sum(1 for row in csv_reader)
        
        result = f"列数: {num_columns}, 行数: {num_rows}"
        filename = csvfile.filename
        session['result'] = result  # 結果をセッションに保存
        session['filename'] = filename  # ファイル名もセッションに保存

        return render_template('index.html', result=result, filename=filename)
    
    except Exception as e:
        return f"エラーが発生しました: {str(e)}"

if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSVファイルアップロード</title>
</head>
<body>
    <h2>CSVファイルをアップロードしてください</h2>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="csvfile" accept=".csv">
        <button type="submit">ファイルをアップロード</button>
    </form>

    <!-- 結果を表示する領域 -->
    {% if result %}
    <div style="margin-top: 20px;">
        <h3>最後にアップロードされたCSVファイルの情報:</h3>
        <p>ファイル名: {{ filename }}</p>
        <p>{{ result }}</p>
    </div>
    {% endif %}
</body>
</html>

サーバーの実行

python app.py

クライアント

http://127.0.0.1:5000/ にアクセス

image.png

CSV をアップロードした後の画面

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?