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?

PythonのBottleの初心者向け完全版チュートリアル

Posted at

はじめに

Bottleは、PythonでWebアプリケーションを簡単に作成するための軽量なマイクロフレームワークです。このガイドでは、Bottleを使ってWebアプリケーションを構築する方法を15の章に分けて詳しく説明します。

第1章: Bottleのインストール

Bottleを始めるには、まずインストールが必要です。以下のコマンドを使用してインストールできます。

pip install bottle

第2章: 基本的なアプリケーションの作成

Bottleの基本的なアプリケーションを作成します。

from bottle import route, run

@route('/')
def home():
    return "Hello, Bottle!"

run(host='localhost', port=8080)

このコードは、localhost:8080で"Hello, Bottle!"を表示するシンプルなWebサーバーを起動します。

第3章: ルーティング

Bottleでは、URLに基づいて関数を呼び出すルーティングが可能です。

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

/hello/Johnにアクセスすると、"Hello, John!"が表示されます。

第4章: 静的ファイルの提供

静的ファイル(画像、CSS、JavaScriptなど)を提供する方法を学びます。

from bottle import static_file

@route('/static/<filename>')
def server_static(filename):
    return static_file(filename, root='/path/to/static/files')

第5章: テンプレートの使用

Bottleはテンプレートエンジンをサポートしており、HTMLを動的に生成できます。

from bottle import template

@route('/hello/<name>')
def greet(name):
    return template('<b>Hello {{name}}</b>!', name=name)

第6章: フォームデータの処理

フォームから送信されたデータを処理する方法を説明します。

from bottle import request

@route('/login', method='POST')
def login():
    username = request.forms.get('username')
    password = request.forms.get('password')
    return f"Welcome, {username}!"

第7章: リダイレクト

ユーザーを別のページにリダイレクトする方法を学びます。

from bottle import redirect

@route('/old-page')
def old_page():
    redirect('/new-page')

第8章: エラーハンドリング

エラーハンドリングの方法を説明します。

from bottle import error

@error(404)
def error404(error):
    return 'Nothing here, sorry!'

第9章: JSONレスポンス

JSONデータを返す方法を学びます。

import json

@route('/api/data')
def data():
    return json.dumps({'key': 'value'})

第10章: プラグインの使用

Bottleのプラグインを利用して機能を拡張します。

from bottle.ext import sqlite

app = bottle.Bottle()
plugin = sqlite.Plugin(dbfile='/path/to/db.sqlite')
app.install(plugin)

@app.route('/show/<item>')
def show(item, db):
    row = db.execute('SELECT * FROM items WHERE name=?', (item,)).fetchone()
    return {'item': row}

第11章: セッション管理

セッションを使用してユーザーの状態を管理します。

from bottle import request, response
import uuid

@route('/set_session')
def set_session():
    session_id = str(uuid.uuid4())
    response.set_cookie('session_id', session_id, secret='some-secret-key')
    return "Session set!"

@route('/get_session')
def get_session():
    session_id = request.get_cookie('session_id', secret='some-secret-key')
    return f"Session ID: {session_id}"

第12章: データベースの接続

データベースと接続してデータを操作します。

import sqlite3

@route('/items')
def list_items():
    conn = sqlite3.connect('example.db')
    c = conn.cursor()
    c.execute('SELECT * FROM items')
    rows = c.fetchall()
    conn.close()
    return {'items': rows}

第13章: ミドルウェアの使用

ミドルウェアを使用してリクエストとレスポンスを処理します。

def simple_middleware(callback):
    def wrapper(*args, **kwargs):
        print("Before request")
        response = callback(*args, **kwargs)
        print("After request")
        return response
    return wrapper

app = bottle.Bottle()
app.add_hook('before_request', simple_middleware)

第14章: デプロイメント

Bottleアプリケーションを本番環境にデプロイする方法を学びます。

# Using a WSGI server like Gunicorn
# Install Gunicorn: pip install gunicorn
# Run: gunicorn myapp:app

GunicornなどのWSGIサーバーを使用して、アプリケーションを本番環境で実行します。これにより、より効率的でスケーラブルなアプリケーションが実現します。

第15章: セキュリティのベストプラクティス

Bottleアプリケーションを安全に保つためのベストプラクティスを紹介します。

  • 入力データのバリデーションを行う: ユーザーからの入力を常に検証し、SQLインジェクションやXSS攻撃を防ぎます。
  • HTTPSを使用する: 通信を暗号化することで、データの盗聴を防ぎます。
  • セッション管理を適切に行う: セッションIDを安全に管理し、セッション固定攻撃を防ぎます。

第16章: サンプルメンバーシップアプリケーションの構築

ここでは、Bottleを使用してシンプルなメンバーシップアプリケーションを構築します。

データベースのセットアップ

まず、SQLiteデータベースを設定します。

import sqlite3

def init_db():
    conn = sqlite3.connect('membership.db')
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY,
            username TEXT UNIQUE,
            password TEXT
        )
    ''')
    conn.commit()
    conn.close()

init_db()

ユーザー登録

ユーザーが登録できるようにします。

from bottle import request, response, template

@route('/register', method=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.forms.get('username')
        password = request.forms.get('password')
        conn = sqlite3.connect('membership.db')
        c = conn.cursor()
        try:
            c.execute('INSERT INTO users (username, password) VALUES (?, ?)', (username, password))
            conn.commit()
            return "Registration successful!"
        except sqlite3.IntegrityError:
            return "Username already exists!"
        finally:
            conn.close()
    return template('register_form')

ログイン機能

ユーザーがログインできるようにします。

@route('/login', method=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.forms.get('username')
        password = request.forms.get('password')
        conn = sqlite3.connect('membership.db')
        c = conn.cursor()
        c.execute('SELECT * FROM users WHERE username=? AND password=?', (username, password))
        user = c.fetchone()
        conn.close()
        if user:
            response.set_cookie('account', username, secret='some-secret-key')
            return "Login successful!"
        else:
            return "Login failed!"
    return template('login_form')

ユーザー情報の表示

ログインしたユーザーの情報を表示します。

@route('/profile')
def profile():
    username = request.get_cookie('account', secret='some-secret-key')
    if username:
        return f"Welcome, {username}!"
    else:
        return "You are not logged in."

テンプレートファイル

register_form.tpllogin_form.tplというテンプレートファイルを作成します。

register_form.tpl:

<form action="/register" method="post">
    Username: <input name="username" type="text" />
    Password: <input name="password" type="password" />
    <input value="Register" type="submit" />
</form>

login_form.tpl:

<form action="/login" method="post">
    Username: <input name="username" type="text" />
    Password: <input name="password" type="password" />
    <input value="Login" type="submit" />
</form>

このガイドを通じて、Bottleを使用したWebアプリケーション開発の基本を理解し、より高度な機能を実装できるようになることを願っています。Happy coding!

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?