はい、Pythonの軽量WebフレームワークであるBottleを使って、仮想環境で環境構築を行い、SQLite3を利用したWebアプリケーションを開発する手順を具体的に説明します。
1. 環境構築
- プロジェクトディレクトリの作成:
C:\projects\bottle_app
のようなディレクトリを作成します。
- 仮想環境の作成:
- コマンドプロンプトでプロジェクトディレクトリに移動し、仮想環境を作成します。
bash cd C:\projects\bottle_app python -m venv venv
- 仮想環境を有効化します。
bash venv\Scripts\activate
(プロンプトの先頭に(venv)
と表示されれば成功です)
- コマンドプロンプトでプロジェクトディレクトリに移動し、仮想環境を作成します。
- Bottleのインストール:
bash pip install bottle
(この段階で、他に利用したいライブラリがあればインストールします。)
2. アプリケーション開発
ディレクトリ構成:
C:\projects\bottle_app
ディレクトリ内に、以下のファイルを作成します。
app.py
: メインのアプリケーションロジック
views
ディレクトリ: HTMLテンプレートを格納
index.tpl
: トップページ
create.tpl
: 新規データ登録フォーム
edit.tpl
: データ編集フォーム
view.tpl
: 詳細データ表示
bottle_app.db
: SQLite3データベース
app.py の実装:
import sqlite3
from bottle import route, run, request, template, redirect
import os
DB_PATH = 'bottle_app.db'
# データベース接続
def get_db_connection():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
# テーブル作成
def create_table():
conn = get_db_connection()
conn.execute('''
CREATE TABLE IF NOT EXISTS items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
description TEXT
)
''')
conn.commit()
conn.close()
create_table() #アプリ起動時にテーブルがなければ作成
# ルート設定
@route('/')
def index():
conn = get_db_connection()
items = conn.execute('SELECT * FROM items').fetchall()
conn.close()
return template('views/index', items=items)
@route('/create', method='GET')
def create_get():
return template('views/create')
@route('/create', method='POST')
def create_post():
name = request.forms.get('name')
description = request.forms.get('description')
conn = get_db_connection()
conn.execute('INSERT INTO items (name, description) VALUES (?, ?)', (name, description))
conn.commit()
conn.close()
return redirect('/')
@route('/edit/<id:int>', method='GET')
def edit_get(id):
conn = get_db_connection()
item = conn.execute('SELECT * FROM items WHERE id = ?', (id,)).fetchone()
conn.close()
return template('views/edit', item = item)
@route('/edit/<id:int>', method='POST')
def edit_post(id):
name = request.forms.get('name')
description = request.forms.get('description')
conn = get_db_connection()
conn.execute('UPDATE items SET name = ?, description = ? WHERE id = ?', (name, description, id))
conn.commit()
conn.close()
return redirect('/')
@route('/view/<id:int>')
def view(id):
conn = get_db_connection()
item = conn.execute('SELECT * FROM items WHERE id = ?', (id,)).fetchone()
conn.close()
return template('views/view', item=item)
@route('/delete/<id:int>')
def delete(id):
conn = get_db_connection()
conn.execute('DELETE FROM items WHERE id = ?', (id,))
conn.commit()
conn.close()
return redirect('/')
if __name__ == '__main__':
run(host='localhost', port=8080, debug = True)
HTMLテンプレート (viewsディレクトリ内):
views/index.tpl (一覧表示)
<!DOCTYPE html>
<html>
<head>
<title>Bottle App</title>
</head>
<body>
<h1>Items List</h1>
<a href="/create">Add New Item</a>
<ul>
%for item in items:
<li><a href="/view/{{item['id']}}">{{item['name']}}</a>
<a href="/edit/{{item['id']}}">Edit</a>
<a href="/delete/{{item['id']}}">Delete</a>
</li>
%end
</ul>
</body>
</html>
views/create.tpl (新規作成フォーム)
<!DOCTYPE html>
<html>
<head>
<title>Create Item</title>
</head>
<body>
<h1>Create New Item</h1>
<form method="POST">
<label>Name: </label><input type="text" name="name" required><br>
<label>Description: </label><input type="text" name="description"><br>
<button type="submit">Submit</button>
</form>
<a href="/">Back to Item List</a>
</body>
</html>
views/edit.tpl (編集フォーム)
<!DOCTYPE html>
<html>
<head>
<title>Edit Item</title>
</head>
<body>
<h1>Edit Item</h1>
<form method="POST">
<label>Name:</label> <input type="text" name="name" value="{{item['name']}}" required><br>
<label>Description:</label><input type="text" name="description" value="{{item['description']}}"><br>
<button type="submit">Update</button>
</form>
<a href="/">Back to Item List</a>
</body>
</html>
```
* `views/view.tpl` (詳細表示)
```html
<!DOCTYPE html>
<html>
<head>
<title>Item Details</title>
</head>
<body>
<h1>Item Details</h1>
<p>Name: {{item['name']}}</p>
<p>Description: {{item['description']}}</p>
<a href="/">Back to Item List</a>
</body>
</html>
```
**3. アプリケーションの実行**
1. **コマンドプロンプトで仮想環境を有効化していることを確認:**
* `(venv)` が表示されている状態であることを確認します。
2. **`app.py` を実行:**
```bash
python app.py
```
* `http://localhost:8080` にアクセスすると、アプリケーションが表示されます。
**開発手順のポイント**
* **仮想環境:** プロジェクトごとに仮想環境を作成することで、ライブラリのバージョンを分離し、依存関係による問題を避けることができます。
* **SQLite3:**
* `sqlite3` モジュールを使ってデータベースに接続し、SQLクエリを実行します。
* テーブルの作成は、アプリケーション起動時などに1度だけ実行すればOKです。
* **Bottle:**
* `@route` デコレータでURLと対応する関数を関連付けます。
* `request` オブジェクトで、フォームデータやクエリパラメータを取得します。
* `template()` 関数でHTMLテンプレートをレンダリングします。
* `redirect()` 関数で、別のURLにリダイレクトします。
* **HTMLテンプレート:**
* Bottleのテンプレートエンジン(デフォルトはsimple-template)を使用して、Pythonの変数をHTMLに埋め込むことができます。
* `%` で始まるコードを記述することで、ループ処理や条件分岐などを行うことができます。
**具体的な開発の進め方**
1. **要件定義:** まずはどんな機能が必要なのかを明確にします。
* データの一覧表示、登録、編集、削除など、基本的なCRUD操作を中心に考えてみます。
2. **データベース設計:** 必要なテーブルとそのカラムを定義します。
* 例えば、`items` テーブルには、`id`, `name`, `description` のようなカラムを設定します。
3. **ルート設計:** URLと対応する処理(関数)を定義します。
* トップページ(`/`)、新規作成(`/create`)、編集(`/edit/<id>`)、詳細表示(`/view/<id>`) のようなルートを作成します。
4. **HTMLテンプレート作成:**
* 各ページに対応するHTMLテンプレートを作成します。
5. **Pythonコード実装:**
* ルートに対応するPythonの関数を実装します。
* データベースとの接続、データの取得、登録、更新、削除などを実装します。
* テンプレートをレンダリングする処理を記述します。
6. **動作確認とデバッグ:**
* Webブラウザでアクセスし、動作を確認します。
* エラーが発生した場合は、デバッグを行い、修正します。
7. **リファクタリング:**
* コードを整理し、可読性や保守性を高めます。
**まとめ**
この手順に従って、BottleとSQLite3を使ったWebアプリケーションを開発できます。最初はシンプルなアプリケーションから始め、徐々に機能を拡張していくのがおすすめです。
Bottleの公式ドキュメント([https://bottlepy.org/docs/dev/](https://bottlepy.org/docs/dev/)) も参考にしてください。
もし、さらに具体的な質問や不明な点があれば、お気軽にご質問ください。
コメント