Drafts

@cm3 の草稿置場 / 少々Wikiっぽく使っているので中身は適宜追記修正されます。

Python BottleAPI のデモを作る。foreverで管理する。Nginx を前に置く。Python 3.4 を使っている。

基本方針

nginx の設定

ポートはもちろん、スクリプトrun(host='localhost', port=3030)の部分と対応させる

location /app/hogehoge/ {
  proxy_pass http://127.0.0.1:3030/;
}

メインのスクリプト

適宜抽象化してるがだいたいこんな感じ。demo のところに html と js でデモを作成している。

from bottle import response, route, run, static_file
import json
import logging
logging.basicConfig(filename='debug.log',level=logging.DEBUG)

@route('/')
def readme():
    response.content_type = 'text/markdown'
    return static_file("README.md", root='./')

@route('/api/<data>')
def api(data):
    response.content_type = 'application/json'
    # 本当はここにいろいろ処理が入る
    return json.dumps([data])

@route('/demo/<filepath:path>')
def server_static(filepath):
    return static_file(filepath, root='./demo')

if __name__ == '__main__':
    # コマンドから"python3 test.py"で起動した場合
    run(host='localhost', port=3030)

forever の使い方

forever start -c python test.py みたいな形で使う。そもそも python test.py でエラーを吐く場合は立ち上がらない(STOPPEDになる)ので、注意。その場合、アクセスは Nginx から 502 Bad Gateway を返されるかな。

forever list で状態を把握し、適宜forever stop [id]で落としたり、forever restart [id]でファイルを読み込み直したりするとよい。

参考:

Python 部分をデバッグする

-o オプションで stdout が出力できるとあるが、うまくいかなかった。logging モジュール使ってファイルに出力するのがいいのじゃないか。

参考:

APIへの入力フォーム

Ajax の基本的なテクニックを使う。

$(document).ready(function(){
    $('#form').submit(function(event) {
        event.preventDefault();
        $.ajax({
            url: '../api/'+$("#input").val().split(" ").join("+"),
            dataType: 'json',
            success : function(data) {
                //取得した data に対する処理
                $("#result").text(JSON.stringify(data))
            },
            //二重送信防止
            beforeSend: function(xhr, settings) {
                $("#submit").attr('disabled', true);
            },
            complete: function(xhr, textStatus) {
                $("#submit").attr('disabled', false);
            },
        })
    });
});

参考:

APIから出力する

Bottle で json を出力するのは

import json

@route('/api/<data>')
def api(data):
    response.content_type = 'application/json'
    return json.dumps([data])

みたいにすればいい。

参考:

APIからの出力を受け取って表示する

id が result の div に流し込むなら

$("#result").text(JSON.stringify(data))

みたいな感じ。上記 APIへの入力フォーム の success 部に書くだけ。

その他

nginxの設定はシンプルに

location ~ ^/app/hogehoge/(.*)$ {
  proxy_pass http://127.0.0.1:3030/$1;
}

ではなく、

location /app/hogehoge/ {
  proxy_pass http://127.0.0.1:3030/;
}

のようにシンプルにしないとなんかのモジュールが動かなかった。