hgwebをwsgi middlewareにして必要に応じて(hg cloneの場合に)hgwebに処理を移譲する

方法を調べていました。rhodecodeの丸パクリです。application/mercurialなんてのがあるんですね。
動かすにはwebobとmercurialが必要です。
repo_name='.'しているのでserverを起動したディレクトリを公開します。

from wsgiref.simple_server import make_server
from webob.dec import wsgify
from mercurial.hgweb import hgweb_mod

# ref: https://bitbucket.org/marcinkuzminski/rhodecode/src/tip/rhodecode/lib/middleware/simplehg.py
@wsgify.middleware
def hgweb(req, app, repo_name):

    def is_mercurial(req):
        http_accept = req.environ['HTTP_ACCEPT']
        return http_accept and http_accept.startswith('application/mercurial')

    def make_hgweb_app(repo_name):
        return hgweb_mod.hgweb(repo_name, name=repo_name)

    if is_mercurial(req):
        return make_hgweb_app(repo_name)
    else:
        return app

@wsgify
def app(req):
    return 'hi'

wrapped = hgweb(app, repo_name='.')

httpd = make_server('', 8000, wrapped)
httpd.serve_forever()