0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flask入門メモ

Last updated at Posted at 2025-05-29

はじめに

RAGの検証を行いたく、簡易にFlaskを使用しているが、簡易とはいえFlask、またPythonもそんなに使っておらず、急ぎ理解したことをメモっておく(すぐに忘れそうなので)。

📝 Flask入門メモ:app.py の役割と初期画面表示の仕組み

✅ Flaskとは?

PythonでWebアプリを簡単に作れる軽量フレームワーク。
ルーティング、テンプレート表示、フォーム送信などがシンプルに実装できる。

✅ 必要なファイル一覧(最小構成)

your_project/
├── app.py
└── templates/
    └── index.html


### Flaskアプリの起動

````markdown
## Flask アプリ起動メモ(開発用)

### 起動方法(直接実行)
```bash
python app.py

app.pyif __name__ == "__main__": が必要

✅ Flaskアプリの基本構成(最小)

app.py

from flask import Flask, request, render_template
from rag_core import get_answer  # 別ファイルで回答処理していると仮定

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def index():
    answer = ""
    if request.method == "POST":
        question = request.form["question"]
        answer = get_answer(question)
    return render_template("index.html", answer=answer)

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

✅ 解釈・処理の流れ

処理内容 解説
app = Flask(__name__) Flaskアプリケーションの本体を作成する
@app.route("/", methods=["GET", "POST"]) / へのアクセス(GET or POST)で index() を呼ぶルーティング設定
def index() 画面表示やフォーム処理を行う関数。POST時はformから質問を取得してAI回答処理を実行
render_template("index.html", answer=answer) templates/index.html を表示し、テンプレートに answer を渡す
if __name__ == "__main__": このファイルが直接実行されたときだけ Flaskサーバーを起動する(app.run()

✅ 初期画面が表示されるまでの流れ

1. ブラウザが http://localhost:5000 にアクセス
2. Flaskが @app.route("/") を検知 → index() を呼ぶ(GET)
3. index() が templates/index.html を返す
4. ブラウザにHTMLが表示される

✅ FlaskのテンプレートHTML(例)

templates/index.html

<!DOCTYPE html>
<html>
<head>
    <title>社内ドキュメントQA</title>
</head>
<body>
    <h1>社内ドキュメントQA</h1>
    <form method="post">
        <input type="text" name="question" placeholder="質問を入力してください">
        <input type="submit" value="送信">
    </form>
    <h3>回答:</h3>
    <p>{{ answer }}</p>
</body>
</html>

✅ その他メモ

  • ファイル名は app.py でなくてもよい(例:main.py
  • Flaskアプリを flask run で起動する方法もある(環境変数を設定する必要あり)
  • __name__ == "__main__" による分岐で、モジュールとして読み込んだときと実行したときの処理を分けている

おわりに

RAGの検証がメインなので、また続きを早めに記載する。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?