Python で blosxom をちょっとアレンンジ

Python で blosxom ! - 女子高生ぷろぐらまーなお☆のブログ

参考に、いろいろ遊んでみました。

#!/usr/bin/env python

import os

opts = {
        'data-dir' : "data",
        'data-ext' : ".txt",
        }

class BlosxomPy:
    class Entry:
        def __init__(self, file, name, time, title, body):
            self.file = file
            self.name = name
            self.time = time
            self.title = title
            self.body = body

    def __init__(self, opts):
        self.opts = opts

    def run(self):
        def sort_by_mtime(a, b):
            return cmp(b.time, a.time)
        entries = self.entries()
        print repr([e.name for e in sorted(entries, sort_by_mtime)])

    def entries(self):
        for path in self.listfiles(opts['data-dir']):
            f = file(path)
            content = f.readlines()

            e = self.Entry(
                    file = path,
                    name = path.replace(opts['data-dir'], '').replace(opts['data-ext'], ''),
                    time  = os.stat(path).st_mtime,
                    title = content[0],
                    body  = content[1:-1])
            yield e

    def listfiles(self, dir):
        dirs = [dir]
        while len(dirs) > 0:
            dir = dirs.pop()
            for file in os.listdir(dir):
                file = os.path.normpath(os.path.join(dir, file))
                if os.path.isdir(file):
                    dirs.append(file)
                else:
                    yield file

BlosxomPy(opts).run()

ポイント。

  • yieldを使った方がpythonicな気がします。
  • でもそれだとそのままentries.sort()できなかったので、sorted()関数を使ってます。
  • Entryに__init__()を作りました。キーワード引数好き好きなので。
  • もうちょっと色々な処理をEntryクラスに移動した方が良いかも。
  • blosxomとしてはまだ全然完成してません(>_<)