LoginSignup
0
3

Flaskを使ったWebアプリの基本的な手順

Last updated at Posted at 2023-12-24

Flaskを使ったWebアプリの基本的な手順

Webアプリケーションを作成してPythonスクリプトを実行する基本的な方法を解説します。Flaskを使用して、簡単かつ効果的にPythonスクリプトをWeb上で実行できるようにします。

Flaskの導入

まずはFlaskをインストールします。ターミナルで以下のコマンドを実行します。

pip install Flask

基本的なFlaskアプリの作成

このFlaskアプリのコードは、Pythonスクリプトをアップロードして実行するシンプルなWebアプリケーションを構築しています。以下にコードの主な処理を説明します。

  1. Flaskアプリケーションの初期化:

    app = Flask(__name__)
    

    Flaskアプリケーションを初期化します。

  2. '/(ルート)'へのルーティング:

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

    ルートパスへのアクセスでは、index.htmlを表示します。これはファイルアップロードフォームを含むメインのページです。

  3. '/execute'へのルーティング(POSTメソッド):

    @app.route('/execute', methods=['POST'])
    def execute_script():
    

    '/execute'パスへのPOSTメソッドによるリクエストがあった場合の処理を定義します。

  4. アップロードされたファイルの処理:

    if 'file' not in request.files:
        return render_template('index.html', message='No file part')
    
    file = request.files['file']
    
    if file.filename == '':
        return render_template('index.html', message='No selected file')
    

    リクエストからファイルが送信されているかどうか、およびファイルが選択されているかどうかを確認します。

  5. アップロードされたスクリプトの保存:

    file.save('uploaded_script.py')
    

    アップロードされたPythonスクリプトをサーバー上に保存します。

  6. Pythonスクリプトの実行:

    result = subprocess.run(['python', 'uploaded_script.py'], capture_output=True)
    

    保存されたPythonスクリプトをsubprocessモジュールを使用して実行します。実行結果はresultに格納されます。

  7. 結果の表示:

    return render_template('index.html', message=result.stdout.decode(), error=result.stderr.decode())
    

    実行結果とエラーメッセージを含むテンプレートindex.htmlを表示します。これにより、ブラウザに結果が表示されます。

  8. Flaskアプリケーションの実行:

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

    スクリプトが直接実行された場合に、Flaskアプリケーションをデバッグモードで実行します。

このコードは簡単な機能を持つWebアプリケーションであり、ファイルのアップロードとPythonスクリプトの実行結果の表示を行います。

Pythonスクリプト以下は全コード

from flask import Flask, render_template, request
import subprocess

app = Flask(__name__)

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

@app.route('/execute', methods=['POST'])
def execute_script():
    if 'file' not in request.files:
        return render_template('index.html', message='No file part')

    file = request.files['file']

    if file.filename == '':
        return render_template('index.html', message='No selected file')

    file.save('uploaded_script.py')
    result = subprocess.run(['python', 'uploaded_script.py'], capture_output=True)

    return render_template('index.html', message=result.stdout.decode(), error=result.stderr.decode())

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

フロントエンドの設計

HTMLテンプレート(index.html)を作成し、ファイルアップロードと実行結果の表示を行います。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Python Script Executor</title>
</head>
<body>
    <h1>Python Script Executor</h1>
    <form action="/execute" method="post" enctype="multipart/form-data">
        <input type="file" name="file" accept=".py">
        <input type="submit" value="Upload and Execute">
    </form>
    {% if message %}
        <h2>Result:</h2>
        <pre>{{ message }}</pre>
    {% endif %}
    {% if error %}
        <h2>Error:</h2>
        <pre>{{ error }}</pre>
    {% endif %}
</body>
</html>

結論

これで、Flaskを使用してPythonスクリプトを実行するWebアプリを構築しました。ファイルをアップロードし、ボタンをクリックするだけでPythonスクリプトを実行し、その結果をブラウザ上で表示できます。

0
3
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
3