0
0

More than 1 year has passed since last update.

Pythonで簡単なMVCモデルのコードを書いてみた

Last updated at Posted at 2022-12-19

はじめに

MVCモデルは、Webアプリケーションを作成する際によく使われるアーキテクチャパターンです。MVCはModel-View-Controllerの略で、それぞれ以下のような役割を果たします。

各MVCの要素について

Model
データを管理する部分。データベースやAPIからデータを取得したり、更新したりする処理を担当する。

View
ユーザーに表示される部分。HTMLやCSS、JavaScriptなどを使って、Webページを作成する。

Controller
ModelとViewをつなぐ部分。HTTPリクエストを受け取り、適切なModelからデータを取得し、Viewに渡す処理を担当する。

MVCモデルを使用すると、アプリケーションをわかりやすく構造化できるため、開発をスムーズに進めることができます。

コード

以下に、MVCモデルを使用したPythonでのWebアプリケーションの例を示します。

from flask import Flask, render_template, request

# Model
class Task:
    def __init__(self, description, status):
        self.description = description
        self.status = status

# View
app = Flask(__name__)

@app.route('/')
def index():
    tasks = [
        Task('Finish homework', 'in progress'),
        Task('Buy groceries', 'done')
    ]
    return render_template('index.html', tasks=tasks)

# Controller
if __name__ == '__main__':
    app.run()

※FWにFlaskを使用しています

TaskクラスがModelで、index関数がControllerで、index.htmlがViewです。index関数は、Taskクラスのインスタンスを作成し、render_template関数を使用してHTMLページを生成します。HTMLページには、Taskクラスのdescriptionとstatusを表示するようになっています。

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