ななぶろ

-お役立ち情報を気楽に紹介するブログ-

Flaskプログラミング練習問題:Webアプリケーション開発の基礎と実践

www.amazon.co.jp

Flaskプログラミング練習問題:Webアプリケーション開発の基礎と実践

はじめに

FlaskはPythonでWebアプリケーションを構築するための軽量かつ柔軟なマイクロフレームワークです。Djangoのようなフルスタックフレームワークと比較すると、よりシンプルで、必要な機能だけを追加できるため、小規模なプロジェクトやAPIの開発に適しています。本記事では、Flaskの基本的な概念から実践的な応用までを網羅し、20個の問題を通してステップバイステップで学習を進めていきます。各問題には詳細な解説とヒントが用意されており、初心者の方でも無理なく理解できるよう工夫しました。

Introduction: Flask is a lightweight and flexible microframework for building web applications in Python. Compared to full-stack frameworks like Django, it's simpler and allows you to add only the necessary features, making it suitable for small projects and API development. This article covers the basics of Flask to practical applications through 20 problems, allowing you to learn step by step. Each problem has detailed explanations and hints, designed to be easily understood even by beginners.

1. Flaskのインストールと基本的なアプリケーションの作成

まず最初に、Flaskをインストールし、最もシンプルなWebアプリケーションを作成することで、環境構築と基本的な動作を確認します。

Installing Flask and Creating a Basic Application: First, install Flask and create the simplest web application to set up your environment and verify basic functionality.

問題1: Flaskをインストールし、「Hello, World!」と表示するシンプルなWebアプリケーションを作成してください。

Problem 1: Install Flask and create a simple web application that displays "Hello, World!".

解説:

Flaskのインストールは、pipというPythonのパッケージマネージャーを使って簡単に行えます。ターミナルまたはコマンドプロンプトを開き、以下のコマンドを実行します。

pip install flask

次に、app.pyという名前のファイルを作成し、以下のコードを記述します。

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "Hello, World!"

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

このコードは、Flaskアプリケーションのインスタンスを作成し、ルートURL(/)にアクセスがあった場合に「Hello, World!」という文字列を返すWebアプリケーションです。

  • from flask import Flask: FlaskモジュールからFlaskクラスをインポートします。これは、Flaskフレームワークを使用するために必要な処理です。
  • app = Flask(__name__): Flaskアプリケーションのインスタンスを作成します。__name__は、現在のモジュールの名前を表し、Flaskが適切なリソースを見つけるために使用されます。
  • @app.route("/"): ルートURL(/)にアクセスがあった場合に実行される関数を定義します。このデコレーターは、URLと関数を結びつけます。
  • def hello_world():: 実際にWebページの内容を返す関数です。ここでは単なる文字列を返していますが、HTMLコードや他のデータも返せます。
  • return "Hello, World!": HTTPレスポンスとして「Hello, World!」という文字列を返します。ブラウザに表示されるのはこの文字列です。
  • if __name__ == "__main__":: このスクリプトが直接実行された場合にのみ、以下のコードを実行します。これにより、モジュールとしてインポートされた場合にはサーバーが起動しないようにします。
  • app.run(debug=True): Flask開発サーバーを起動します。debug=Trueとすることで、コードの変更を自動的に検出し、サーバーを再起動してくれます。これは開発時に非常に便利です。

このファイルを保存し、ターミナルでpython app.pyを実行すると、Flask開発サーバーが起動し、ブラウザでhttp://127.0.0.1:5000/にアクセスすることで「Hello, World!」と表示されるはずです。

Explanation: Installing Flask is easy using pip, Python's package manager. Open your terminal or command prompt and run the following command:

pip install flask

Next, create a file named app.py and enter the following code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "Hello, World!"

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

This code creates a web application that returns the string "Hello, World!" when accessed at the root URL (/).

  • from flask import Flask: Imports the Flask class from the flask module.
  • app = Flask(__name__): Creates an instance of the Flask application. __name__ represents the current module's name, used by Flask to find resources.
  • @app.route("/"): Defines a function that will be executed when the root URL (/) is accessed. This decorator links the URL and the function.
  • def hello_world():: The function that actually returns the content of the web page. It currently returns just a string, but could return HTML or other data.
  • return "Hello, World!": Returns the string "Hello, World!" as an HTTP response. This is what will be displayed in the browser.
  • if __name__ == "__main__":: Only executes the following code if this script is run directly (not imported as a module).
  • app.run(debug=True): Starts the Flask development server. debug=True enables automatic reloading when you make changes to your code, which is very useful during development.

Save the file and run it in your terminal with python app.py. The Flask development server will start, and you should see "Hello, World!" displayed in your browser at http://127.0.0.1:5000/.

はじめに

Flaskは、PythonでWebアプリケーションを開発するための軽量なマイクロフレームワークです。Djangoのようなフルスタックフレームワークと比較して、よりシンプルで柔軟性があり、必要な機能だけを追加できるという特徴があります。本記事では、Flaskの基礎から応用までを段階的に解説し、読者がFlaskを使ってWebアプリケーションを構築できるようになることを目指します。

Introduction: Flask is a lightweight microframework for developing web applications in Python. Compared to full-stack frameworks like Django, it's more simple and flexible, allowing you to add only the features you need. This article will progressively explain the basics and advanced concepts of Flask, aiming to enable readers to build web applications using it.

1. Flaskのインストールと基本的なアプリケーションの作成

Flaskを始めるには、まずインストールが必要です。その後、シンプルなWebアプリケーションを作成し、動作を確認します。

Installing and Creating a Basic Application: To get started with Flask, you first need to install it. Then, create a simple web application and verify that it works.

問題1: Flaskをインストールし、「Hello, World!」と表示するシンプルなWebアプリケーションを作成してください。

解説:

Flaskはpipを使って簡単にインストールできます。ターミナルまたはコマンドプロンプトで以下のコマンドを実行します。

pip install flask

次に、app.pyというファイルを作成し、以下のコードを記述します。

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "Hello, World!"

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

このコードは、Flaskアプリケーションを作成し、ルートURL(/)にアクセスがあった場合に「Hello, World!」という文字列を返すWebアプリケーションです。

  • from flask import Flask: FlaskモジュールからFlaskクラスをインポートします。これは、Flaskの主要な機能を利用するために必要です。
  • app = Flask(__name__): Flaskアプリケーションのインスタンスを作成します。__name__は、現在のモジュールの名前を表します。この情報は、Flaskが適切なリソースを見つけるために使用されます。
  • @app.route("/"): ルートURL(/)にアクセスがあった場合に実行される関数を定義します。このデコレーターは、URLと関数を結びつける役割を果たします。これにより、特定のURLへのアクセス時に特定のアクションを実行できます。
  • def hello_world():: 実際にWebページの内容を返す関数です。ここでは単なる文字列を返していますが、HTMLコードや他のデータも返せます。この関数は、クライアントに送信されるレスポンスを生成します。
  • return "Hello, World!": HTTPレスポンスとして「Hello, World!」という文字列を返します。これは、ブラウザに表示されるテキストです。
  • if __name__ == "__main__":: このスクリプトが直接実行された場合にのみ、以下のコードを実行します。これにより、このファイルがインポートされた場合(別のモジュールから呼び出された場合)には、サーバーは起動しません。
  • app.run(debug=True): Flask開発サーバーを起動します。debug=Trueとすることで、コードの変更を自動的に検出し、サーバーを再起動してくれます。これにより、開発中に迅速にテストを行い、問題を特定しやすくなります。

このファイルを保存し、ターミナルでpython app.pyを実行すると、Flask開発サーバーが起動し、ブラウザでhttp://127.0.0.1:5000/にアクセスすることで「Hello, World!」と表示されるはずです。

Explanation: To start with Flask, you first need to install it using pip. Open your terminal or command prompt and run the following command: pip install flask. Then, create a file named app.py and add the following code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "Hello, World!"

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

This code creates a Flask application and returns the string "Hello, World!" when someone accesses the root URL (/). Save this file and run it in your terminal using python app.py. This will start the Flask development server, and you should see "Hello, World!" displayed in your browser when you access http://127.0.0.1:5000/.

2. 変数を使った動的なコンテンツの生成

Webアプリケーションでは、ユーザーからの入力やデータベースの情報に基づいて、動的にコンテンツを生成することが重要です。Flaskでは、URLパラメータを使って変数を渡すことができます。

Generating Dynamic Content with Variables: In web applications, it's important to generate content dynamically based on user input or database information. Flask allows you to pass variables using URL parameters.

問題2: URLに渡された名前を表示するWebアプリケーションを作成してください。例えば、http://127.0.0.1:5000/hello/Johnにアクセスすると「Hello, John!」と表示されるようにします。

Explanation: Flask allows you to receive parameters using URL variables. Here's how you can create a web application that displays the name passed in the URL:

from flask import Flask

app = Flask(__name__)

@app.route("/hello/<name>")
def hello(name):
    return f"Hello, {name}!"

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

The @app.route("/hello/<name>") decorator defines a route that accepts a variable named name. The function hello(name) then takes this name as an argument and returns a greeting string. When you access http://127.0.0.1:5000/hello/John, the application will display "Hello, John!".

3. HTMLテンプレートの利用

HTMLテンプレートを使用することで、Webページの構造を定義し、動的なコンテンツを埋め込むことができます。Flaskでは、Jinja2というテンプレートエンジンが使用されています。

Using HTML Templates: Using HTML templates allows you to define the structure of your web pages and embed dynamic content. Flask uses Jinja2 as its template engine.

問題3: 「Hello, World!」と表示するHTMLテンプレートを作成し、それをFlaskアプリケーションで利用してください。

Explanation: First, create a directory named templates (if it doesn't exist). Inside this directory, create a file named hello.html and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Hello</title>
</head>
<body>
    <h1>Hello, World!</h1>
</body>
</html>

Then, modify your Flask application code as follows:

from flask import Flask, render_template

app = Flask(__name__)

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

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

The render_template("hello.html") function renders the HTML template and returns it as an HTTP response. When you access http://127.0.0.1:5000/, the content of your HTML template will be displayed.

4. フォームの作成とデータの受け取り

フォームを使用することで、ユーザーからの入力を簡単に受け取ることができます。Flaskでは、WTFormsというライブラリを使ってフォームを作成できます。

Creating and Receiving Data from Forms: Using forms allows you to easily receive input from users. Flask provides the WTForms library for creating forms.

問題4: 名前を入力するフォームを作成し、入力された名前を「Hello, [名前]!」と表示するWebアプリケーションを作成してください。

Explanation: First, install WTForms:

pip install WTForms

Then, modify your Flask application code as follows:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def hello():
    if request.method == "POST":
        name = request.form["name"]
        return f"Hello, {name}!"
    else:
        return render_template("hello_form.html")

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

Create an HTML file named hello_form.html inside the templates directory and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Hello Form</title>
</head>
<body>
    <h1>Enter your name:</h1>
    <form method="post">
        <input type="text" name="name">
        <button type="submit">Submit</button>
    </form>
</body>
</html>

When you access http://127.0.0.1:5000/, the form will be displayed. After entering your name and submitting, "Hello, [Name]!" will be displayed.

5. セッションの利用

セッションを使用することで、ユーザーに関する情報をサーバー上で一時的に保存できます。Flaskでは、sessionオブジェクトを使ってセッションを管理できます。

Using Sessions: Using sessions allows you to temporarily store information about users on the server. Flask uses the session object to manage sessions.

問題5: 訪問回数をカウントするWebアプリケーションを作成してください。訪問回数はセッションに保存し、ページを開くたびにカウントを増やして表示します。

Explanation:

from flask import Flask, session, render_template

app = Flask(__name__)
app.secret_key = "your secret key"  # セッションの暗号化キーを設定

@app.route("/")
def index():
    if "count" in session:
        session["count"] += 1
    else:
        session["count"] = 1
    return render_template("index.html", count=session["count"])

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

Create an HTML file named index.html inside the templates directory and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Visit Counter</title>
</head>
<body>
    <h1>You have visited this page {{ count }} times!</h1>
</body>
</html>
  • app.secret_key = "your secret key": Sets a secret key for encrypting sessions. Make sure to keep this key confidential and not shared across applications.
  • if "count" in session:: Checks if the count key exists in the session.
  • session["count"] += 1: Increments the value of count in the session.
  • else: session["count"] = 1: If the count key does not exist in the session, initializes it to 1.
  • return render_template("index.html", count=session["count"]): Renders the HTML template and passes the value of count from the session.

When you access http://127.0.0.1:5000/, the number of visits will be displayed. The count increases each time you refresh the page.

6. 静的ファイルの利用

静的ファイル(CSS、JavaScript、画像など)は、Webアプリケーションの見た目や動作を改善するために使用されます。Flaskでは、staticというディレクトリを作成し、その中に静的ファイルを配置することで、簡単にアクセスできるようになります。

問題6: CSSファイルを作成し、それをHTMLテンプレートで利用して、Webページのスタイルを変更してください。

Explanation: First, create a directory named static (if it doesn't exist). Inside this directory, create a file named style.css and add the following code:

body {
    background-color: lightblue;
    font-family: sans-serif;
}
h1 {
    color: navy;
}

Next, modify the code of your HTML template as follows:

<!DOCTYPE html>
<html>
<head>
    <title>Styled Page</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>Hello, World!</h1>
</body>
</html>
  • <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">: Links the style.css file to your HTML template. The function url_for('static', filename='style.css') generates the URL for static files.

Run this code and access http://127.0.0.1:5000/ in your browser, and the background color of the web page will turn light blue, the font will be sans-serif, and the text color of the h1 tag will be navy.

7. エラーハンドリング

Webアプリケーションでは、予期せぬエラーが発生することがあります。Flaskでは、エラーハンドリング機能を使って、エラー発生時に適切なメッセージを表示したり、ログに記録したりすることができます。

問題7: 404エラー(Not Found)ページを作成し、URLが存在しない場合に表示されるようにしてください。

Explanation:

from flask import Flask, render_template

app = Flask(__name__)

@app.errorhandler(404)
def page_not_found(e):
    return render_template("404.html"), 404

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

Create a file named 404.html inside the templates directory and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>404 Not Found</title>
</head>
<body>
    <h1>404 Not Found</h1>
    <p>The page you requested does not exist.</p>
</body>
</html>
  • @app.errorhandler(404): Defines a function that will be executed when a 404 error occurs.
  • def page_not_found(e):: This is the function that receives the 404 error object.
  • return render_template("404.html"), 404: Renders the 404.html template and returns an HTTP status code of 404.

Run this code and access a non-existent URL (e.g., http://127.0.0.1:5000/nonexistent) in your browser, and you will see the message "404 Not Found".

8. Blueprintの利用

Blueprintは、Flaskアプリケーションをモジュール化するための仕組みです。大規模なWebアプリケーションでは、Blueprintを使って機能を分割し、コードの再利用性や保守性を高めることができます。

問題8: 認証機能を持つBlueprintを作成し、それをメインのFlaskアプリケーションに登録してください。

Explanation: First, create a file named auth.py and add the following code:

from flask import Blueprint, render_template

auth = Blueprint("auth", __name__)

@auth.route("/login")
def login():
    return render_template("login.html")

Next, modify the code of your main Flask application as follows:

from flask import Flask
from auth import auth

app = Flask(__name__)
app.register_blueprint(auth, url_prefix="/auth")

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

Create a file named login.html inside the templates directory and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>
    <p>Please enter your credentials.</p>
</body>
</html>
  • auth = Blueprint("auth", __name__): Creates a Blueprint named "auth".
  • @auth.route("/login"): Defines the route URL within the Blueprint.
  • app.register_blueprint(auth, url_prefix="/auth"): Registers the Blueprint with the main Flask application and sets the URL prefix.

Run this code and access http://127.0.0.1:5000/auth/login in your browser, and you will see the message "Login".

9. データベースの利用 (SQLite)

Webアプリケーションでは、データを保存するためにデータベースを使用することがよくあります。Flaskでは、SQLAlchemyというライブラリを使って簡単にデータベースを操作できます。

問題9: SQLiteデータベースを作成し、ユーザー情報を保存するテーブルを作成してください。

Explanation: First, install SQLAlchemy:

pip install SQLAlchemy

Next, modify the code of your Flask application as follows:

from flask import Flask
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from base import Base  # You need to create base.py

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(String)
    email = Column(String)

# Create the database (only execute once)
with app.app_context():
    db.create_all()

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

Create a file named base.py and add the following code:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
  • app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db': Sets the connection string for the SQLite database.
  • db = SQLAlchemy(app): Creates a SQLAlchemy instance and associates it with the Flask application.
  • class User(Base):: Defines the table for storing user information.
  • db.create_all(): Creates the database and tables (execute only once).

Running this code will create an SQLite database file named users.db and a table named users.

10. REST APIの構築 (JSON)

Webアプリケーションでは、他のアプリケーションやデバイスとデータをやり取りするためにREST APIを構築することがあります。Flaskでは、jsonify関数を使って簡単にJSONレスポンスを生成できます。

問題10: ユーザー情報をJSON形式で返すAPIを作成してください。

Explanation:

from flask import Flask, jsonify
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from base import Base
from flask import Flask

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(String)
    email = Column(String)

with app.app_context():
    Base.metadata.create_all(db.engine)  # Create the database and tables

@app.route("/api/users")
def get_users():
    session = sessionmaker(bind=db.engine)()
    users = session.query(User).all()
    user_list = []
    for user in users:
        user_list.append({"id": user.id, "username": user.username, "email": user.email})
    session.close()
    return jsonify(user_list)

if __name__ == "__main__":
    app.run(debug=True)
  • @app.route("/api/users"): Defines the function that will be executed when a request is made to the /api/users URL.
  • jsonify(user_list): Converts the Python list to JSON format and returns it as an HTTP response.

Running this code and accessing http://127.0.0.1:5000/api/users in a browser will display the JSON data for users.

はじめに

Flaskは、PythonでWebアプリケーションを開発するための軽量なマイクロフレームワークです。そのシンプルさと柔軟性から、小規模なAPIやプロトタイプから、大規模なWebアプリケーションまで、幅広い用途で利用されています。本記事では、Flaskの基礎から応用までを網羅し、初心者の方でも段階的に学習できるように20問の問題と解説を用意しました。各問題には具体的なコード例と詳細な説明が含まれており、読者の皆様がFlaskの知識とスキルを習得する手助けとなることを目指します。

1. Flaskのインストールと基本的なアプリケーションの作成

まず最初に、Flaskをインストールし、最もシンプルなWebアプリケーションを作成してみましょう。これは、Flaskの環境構築と基本的な動作を確認するための最初のステップです。

問題1: Flaskをインストールし、「Hello, World!」と表示するシンプルなWebアプリケーションを作成してください。

解説:

FlaskはpipというPythonのパッケージ管理システムを使って簡単にインストールできます。ターミナルまたはコマンドプロンプトを開き、以下のコマンドを実行します。

pip install flask

次に、app.pyという名前のファイルを作成し、以下のコードを記述します。

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "Hello, World!"

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

このコードは、Flaskアプリケーションを作成し、ルートURL(/)にアクセスがあった場合に「Hello, World!」という文字列を返すWebアプリケーションです。

  • from flask import Flask: This line imports the Flask class from the flask module. This is necessary to create a Flask application instance.
  • app = Flask(__name__): This creates an instance of the Flask class and assigns it to the variable app. The argument __name__ refers to the name of the current module, which helps Flask locate resources like templates and static files.
  • @app.route("/"): This is a decorator that associates the function below with a specific URL route. In this case, the function will be executed when a user visits the root URL (/).
  • def hello_world():: This defines the function that will handle requests to the root URL. It returns the string "Hello, World!".
  • return "Hello, World!": This line returns the string "Hello, World!" as an HTTP response. The browser will display this string on the page.
  • if __name__ == "__main__":: This is a standard Python idiom that checks if the script is being run directly (as opposed to being imported as a module). If it is, the code inside the if block will be executed.
  • app.run(debug=True): This starts the Flask development server and makes your application accessible in a web browser. The debug=True argument enables debugging mode, which provides helpful error messages and automatically reloads the server when you make changes to your code.

このファイルを保存し、ターミナルでpython app.pyを実行すると、Flask開発サーバーが起動します。ブラウザを開き、http://127.0.0.1:5000/にアクセスすることで、「Hello, World!」と表示されるはずです。

2. 変数を使った動的なコンテンツの生成

次に、URLパラメータを使ってWebページのコンテンツを動的に変更する方法を学びましょう。これにより、ユーザー名やIDなどの情報をURLから受け取り、それに基づいて異なるコンテンツを表示することができます。

問題2: URLに渡された名前を表示するWebアプリケーションを作成してください。例えば、http://127.0.0.1:5000/hello/Johnにアクセスすると「Hello, John!」と表示されるようにします。

解説:

Flaskでは、URLの変数を使ってパラメータを受け取ることができます。以下のコードは、URLから名前を取得し、それをHTMLテンプレートに渡して表示する例です。

from flask import Flask

app = Flask(__name__)

@app.route("/hello/<name>")
def hello(name):
    return f"Hello, {name}!"

if __name__ == "__main__":
    app.run(debug=True)
  • @app.route("/hello/<name>"): このデコレーターは、/hello/の後に続く文字列を<name>という変数として受け取ります。これにより、URLから名前を取得できます。
  • def hello(name):: この関数は、URLから取得した名前を引数として受け取ります。
  • return f"Hello, {name}!": f-stringを使って、名前を埋め込んだ文字列を返します。これにより、動的にコンテンツを生成できます。

このコードを実行し、ブラウザでhttp://127.0.0.1:5000/hello/Johnにアクセスすると、「Hello, John!」と表示されます。URLの<name>の部分を変更することで、異なる名前を表示することができます。

3. HTMLテンプレートの利用

Webアプリケーションでは、HTMLを使ってWebページの構造を定義することが一般的です。Flaskでは、Jinja2というテンプレートエンジンを使って、HTMLファイルを作成し、変数や条件分岐などを記述することができます。これにより、動的なコンテンツを効率的に生成できます。

問題3: 「Hello, World!」と表示するHTMLテンプレートを作成し、それをFlaskアプリケーションで利用してください。

解説:

まず、templatesというディレクトリを作成します(もし存在しない場合)。このディレクトリの中に、hello.htmlというファイルを作成し、以下のコードを記述します。

<!DOCTYPE html>
<html>
<head>
    <title>Hello</title>
</head>
<body>
    <h1>Hello, World!</h1>
</body>
</html>

次に、Flaskアプリケーションのコードを以下のように変更します。

from flask import Flask, render_template

app = Flask(__name__)

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

if __name__ == "__main__":
    app.run(debug=True)
  • from flask import Flask, render_template: render_template関数をインポートします。この関数は、HTMLテンプレートをレンダリングするために使用されます。
  • @app.route("/"): ルートURLにアクセスがあった場合に実行される関数です。
  • return render_template("hello.html"): templatesディレクトリにあるhello.htmlファイルをレンダリングし、HTTPレスポンスとして返します。

このコードを実行し、ブラウザでhttp://127.0.0.1:5000/にアクセスすると、HTMLテンプレートの内容が表示されます。Jinja2を使用することで、HTMLファイル内でPythonの変数や制御構造を使用できます。

4. フォームの作成とデータの受け取り

Webアプリケーションでは、ユーザーからの入力を受け取るためにフォームを使用することがよくあります。Flaskでは、WTFormsというライブラリを使って簡単にフォームを作成できます。これにより、フォームのバリデーションやセキュリティ対策を容易に行うことができます。

問題4: 名前を入力するフォームを作成し、入力された名前を「Hello, [名前]!」と表示するWebアプリケーションを作成してください。

解説:

まず、WTFormsをインストールします。

pip install WTForms

次に、Flaskアプリケーションのコードを以下のように変更します。

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def hello():
    if request.method == "POST":
        name = request.form["name"]
        return f"Hello, {name}!"
    else:
        return render_template("hello_form.html")

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

templatesディレクトリの中に、hello_form.htmlというファイルを作成し、以下のコードを記述します。

<!DOCTYPE html>
<html>
<head>
    <title>Hello Form</title>
</head>
<body>
    <h1>Enter your name:</h1>
    <form method="post">
        <input type="text" name="name">
        <button type="submit">Submit</button>
    </form>
</body>
</html>
  • @app.route("/", methods=["GET", "POST"]): ルートURLにGETリクエストとPOSTリクエストの両方を受け付けることを指定します。これにより、フォームの表示(GET)と送信(POST)を同じURLで処理できます。
  • if request.method == "POST":: リクエストがPOSTメソッドの場合、フォームから送信されたデータを受け取ります。
  • name = request.form["name"]: フォームのnameという名前の入力フィールドの値を取得します。request.formは、POSTリクエストで送信されたフォームデータを格納する辞書です。
  • return f"Hello, {name}!": 取得した名前を使ってメッセージを生成し、HTTPレスポンスとして返します。f-stringを使用することで、変数を文字列に埋め込むことができます。
  • else: return render_template("hello_form.html"): リクエストがGETメソッドの場合、フォームを表示するためのHTMLテンプレートをレンダリングします。

このコードを実行し、ブラウザでhttp://127.0.0.1:5000/にアクセスすると、名前を入力するフォームが表示されます。名前を入力して送信すると、「Hello, [名前]!」と表示されます。

5. セッションの利用

セッションは、ユーザーに関する情報をサーバー上で一時的に保存するための仕組みです。Flaskでは、sessionオブジェクトを使ってセッションを管理できます。これにより、