doc.dev1x.org

Bottleについての覚書

ルーティング設定を一箇所にまとめる

from bottle import route, abort

@route('/', method='GET')
def index():
    return "Hello Bottle."
// Laravelのルーティング設定
Route::get('/user', [UserController::class, 'index']);
import bottle
from . import controller

app = bottle.Bottle()
app.route('/', 'GET', controller.index)

エラーを返却する

from bottle import route, abort

@route('/', method='GET')
def index():
    abort(401)

JSONのレスポンスを返却する

from bottle import route, abort

@route('/', method='GET')
def index():
    response.content_type = 'application/json'
    return {'status': 'OK'}

ファイルのアップロード

<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="file" />
</form>
# アップロードされるファイルが1つの場合
@route('/upload', method='POST')
def upload():
    upload_file = request.files.get('<INPUTタグのNAME属性>')    # この例では'file'
    save_path = os.path.join('<ファイル保存パス>', upload_file.filename)
    upload_file.save(save_path)
    return redirect('/')

ファイルアップロード時にRequest Entity Too Large発生

# coding: utf-8

import bottle
app = bottle.Bottle()

# リクエストの最大長を10MBに設定
app.MEMFILE_MAX = 1024 * 1000 * 10

@app.route('/upload', method='POST')
def upload():
    upload_file = request.files.get('<INPUTタグのNAME属性>')    # この例では'file'
    save_path = os.path.join('<ファイル保存パス>', upload_file.filename)
    upload_file.save(save_path)
    return redirect('/')

ファイルのダウンロード

gunicornで起動

# coding: utf-8

import bottle
app = bottle.Bottle()

@app.route('/', method='GET')
def index():
    response.content_type = 'application/json'
    return {'status': 'OK'}
gunicorn -w 1 --bind 0.0.0.0:8080 web:app

プラグイン

プラグイン基礎知識

from bottle import response, install
import time

def stopwatch(callback):
    def wrapper(*args, **kwargs):
        start = time.time()
        body = callback(*args, **kwargs)        # <= コールバック関数を実行
        end = time.time()
        response.headers['X-Exec-Time'] = str(end - start)  # <= レスポンスヘッダーに情報を追加している
        return body
    return wrapper

install(stopwatch)
from bottle import response, install

def my_plugin(callback):
    def wrapper(*args, **kwargs):
        return callback(*args, **kwargs)
    return wrapper

install(my_plugin)

プラグインAPI

# クラス名は任意
class MyPlugin:

    name = 'myplugin'       # <= プラグインの登録名
    api = 2                 # <= プラグインバージョン(現状は2が最新)

    # プラグインの初期化処理
    def __init__(self):
        pass

    # プラグイン登録時に実行される処理
    def setup(self, app):
        pass

    # プラグインのメイン処理
    def apply(self, callback, route):
        def wrapper(*args, **kwargs):
            return callback(*args, **kwargs)
        return wrapper
from bottle import response, install
import MyPlugin

install(MyPlugin())

どのような用途でプラグインを使うか?

参考資料