|
| 1 | +#!/usr/bin/python26 |
| 2 | +# vi:si:et:sw=4:sts=4:ts=4 |
| 3 | +# -*- coding: UTF-8 -*- |
| 4 | +# -*- Mode: Python -*- |
| 5 | +# |
| 6 | +# Copyright (C) 2011 Bertera Pietro |
| 7 | + |
| 8 | +import web |
| 9 | +import mimetypes |
| 10 | + |
| 11 | +import markdown2 |
| 12 | + |
| 13 | +# pages is a list of dictionary: the value of key name represent the name\ |
| 14 | +# of page, the value of link represent the routing pattern, |
| 15 | +# and content_file is the path of markdown file with the page content |
| 16 | +pages = [ |
| 17 | + { "name": "Home", |
| 18 | + "link": "/", |
| 19 | + "content_file": "contents/home.md" |
| 20 | + }, |
| 21 | + { "name": "Info", |
| 22 | + "link": "/info.html", |
| 23 | + "content_file": "contents/info.md" |
| 24 | + }, |
| 25 | + ] |
| 26 | + |
| 27 | +# this is the directory with static files (images, css, ...) |
| 28 | +static_dir = "public" |
| 29 | + |
| 30 | +# the view, layout.html is a template file |
| 31 | +htmlview = web.template.render('views', cache=False, base="layout",\ |
| 32 | + globals={'pages':pages, 'ctx': web.ctx}) |
| 33 | + |
| 34 | +# generic controller for Markdown pages: |
| 35 | +class PageClassTemplate: |
| 36 | + content_file = "" |
| 37 | + |
| 38 | + def GET(self): |
| 39 | + html = markdown2.markdown_path(self.content_file) |
| 40 | + return htmlview.page(html) |
| 41 | + |
| 42 | +# Controller for static files |
| 43 | +class Public: |
| 44 | + def GET(self): |
| 45 | + try: |
| 46 | + file_name = web.ctx.path.split('/')[-1] |
| 47 | + web.header('Content-type', mime_type(file_name)) |
| 48 | + return open('.' + web.ctx.path, 'rb').read() |
| 49 | + except IOError: |
| 50 | + raise web.notfound() |
| 51 | + |
| 52 | +# mime type interpreter |
| 53 | +def mime_type(filename): |
| 54 | + return mimetypes.guess_type(filename)[0] or 'application/octet-stream' |
| 55 | + |
| 56 | +# initialize the application |
| 57 | +myApp = web.application(mapping=(), fvars=globals()) |
| 58 | + |
| 59 | +for page in pages: |
| 60 | + pattern = page["link"] |
| 61 | + globals()[page["name"]] = type(page["name"],\ |
| 62 | + (PageClassTemplate,object,), dict(content_file=page["content_file"])) |
| 63 | + myApp.add_mapping(pattern, page["name"]) |
| 64 | + |
| 65 | +# add static file handler: |
| 66 | +try: |
| 67 | + if static_dir: |
| 68 | + myApp.add_mapping("/%s/.+" % static_dir, "Public") |
| 69 | +except AttributeError: |
| 70 | + pass |
| 71 | + |
| 72 | +# RUN! |
| 73 | +if __name__ == "__main__": |
| 74 | + myApp.run() |
0 commit comments