サイトをFreeBSD10+python3.3+Bottleで作り直すメモ(3)-とりあえず何か書いてみる
- 公開日: 2014/05/10(土) 13:56[JST]
- 更新日: 2022/11/26(土) 19:12[JST]
とりあえずお約束のHello, Worldでも。
hello.py:
# -*- coding: utf-8 -*-
from bottle import route, run, SimpleTemplate
from docutils.core import publish_parts
@route('/hello')
def hello():
rest = '''heading
========'''
settings = {
'initial_header_level': 2,
'doctitle_xform': 0,
}
DIR = '/some/where/'
fp = open(DIR + 'header.tpl')
header_tpl = SimpleTemplate(fp.read())
fp.close()
fp = open(DIR + 'footer.tpl')
footer_tpl = SimpleTemplate(fp.read())
fp.close
tp = ("Hello," , "World!!!")
return header_tpl.render(title='Hello World') + \
publish_parts(rest, writer_name='html4css1', \
settings_overrides=settings)['html_body'] + \
footer_tpl.render(data=tp)
run(host='localhost', port=8080, debug=True, reloader=True)
/some/where/header.tpl:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="ja">
<head>
<title>{{title}}</title>
</head>
<body>
<h1>{{title}}</h1>
<hr>
/some/where/footer.tpl:
<p>
% for msg in data:
{{msg}}
% end
</p>
</body>
</html>
こういうソースを書いて、hello.pyを実行すると、localhost(うちはjail環境だから本当はlocalhost使えないけど)の8080番ポートで開発用のwebサーバが起動して、http://localhost:8080/helloにアクセスすると、下記のソースでページが表示される。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="ja"> <head> <title>Hello World</title> </head> <body> <h1>Hello World</h1> <hr> <div class="document"> <div class="section" id="id1"> <h2>heading</h2> </div> </div> <p> Hello, World!!! </p> </body> </html>
hello.pyの構成はこんな感じ。
Bottleのroute, run ,SimpleTemplateをインポートする
docutilsのpublish_partsもインポートする
@route('/hello')デコレータに続いて関数hello()を記述。関数hello()内では、
変数restにreST文書を代入
変数settingsにreST→HTML変換用のパラメータをセットする。
header.tplとfooter.tplからSimpleTemplateクラスのインスタンスheader_tplとfooter_tplを生成。
関数hello()の返り値として、「header.tpl内の{{title}}を引数title='Hello Worldで置き換えたHTMLコード」「変数restをHTML文書の断片に変換したコード」「『for文で引数tpのタプルの内容を出力する』という構成のfotter.tplから得られるHTMLコード」を結合したテキストを定義。
bottleのrun関数でHTTPサーバを起動。引数debugはテンプレートなりhello.pyのコードにバグがあったときにブラウザにエラー内容を表示する為のフラグで、引数reloaderはhello.pyが書き換わった時に自動的にhello.pyをリスタートさせる為のフラグである。
(2019/11/2追記)これまで publish_parts の writer_name を html4css1 に設定していたが、この設定だとインラインリテラルをTT要素(HTML5では非推奨[1])に変換してあまり論理的じゃない。なんで今後は html5 にしたほうがよさそう。
(2022/11/26追記)writer_name を html4css1 にする場合、 'html_body' ではなく 'body' を指定したほうが良さそう。 'html_body' だと出力が main 要素の中に入れられてしまう。例えばブログ記事一覧表示などで複数のReST文書を変換して1つのドキュメントを作ろうとする場合、 main 要素が複数できてしまう。だが main 要素は1文書あたり一つのみ。(私のサイト、ブログ記事のみGoogle検索に引っかからないという状態が続いているのだがこれが原因なのだろうか?)
(追記終わり)
を付与しています。