Drkcore

27 07 2010 Python Flask Tweet

Flaskでコードをハイライトするサービス

pythonのMarkdownにはPygmentsをつかったコードハイライト用のエクステンションがあるので、それを使えば簡単にかける

flaskmd

スクリーンショット撮ってから「セッションとか使ってないからsessionとかkeyとかいらないじゃん」と思って少し綺麗にしたので最終的には15行くらい。

flaskmd.py

from flask import Flask, request, url_for, render_template
from markdown import markdown

DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)

@app.route('/',methods=['POST', 'GET'])
def show_code(code = ""):
    if request.method == 'POST':
        code = markdown(request.form['code'], ['codehilite'],safe_mode=False)
    return render_template('show_code.html', code=code)

if __name__ == '__main__':
    app.run()

show_code.html

markdownで生成したhtmlをそのままテンプレートに渡すとエスケープされてしまうので、autoescapeをFalseにした。今回ここが一番悩んだがドキュメントをちゃんと読めば書いてあった。

<!doctype html>
<title>CodeHilite</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
<body>
<form action="{{ url_for('show_code') }}" method=post class=add-entry>
<dl>
<dt>code:
<dd><textarea name=code rows=5 cols=40></textarea>
<dd><input type=submit value=hilite>
</dl>
</form>
<div class=page>
  <h1>CodeHilite</h1>
{% autoescape false %}
{{ code }}
{% endautoescape %}
</div>
</body>
</html>

style.css

cssはpygmentsであらかじめファイルに出力しておいた

from pygments.formatters import HtmlFormatter
with open("style.css","a") as f:
    f.write(HtmlFormatter().get_style_defs('.codehilitetable'))

Flask楽しい。

ProductName Lonely Planet Discover Japan
Chris Rowthorn,Andrew Bender,Matthew D. Firestone,Timothy N. Hornyak
Lonely Planet / ¥ 2,326 ()
在庫あり。

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021