返回首页
0
0

初学Tornado,web版的本地文件浏览器

xiaoxin 发表于 2013年03月02日 22:55 | Hits: 2280
Tag: 一些作品

Python有个很好用的库SimpleHTTPServer直接敲
python -mSimpleHTTPServer
就能立刻搭建起一个简易的Server,如果当前目录下没有index.html 或者 index.htm, 则默认将本地所有文件列出来。
近来初学Tornado,用Tornado写一个有类似功能的小脚本作实验

#!/usr/bin/env python
import tornado.ioloop
import tornado.web
import tornado.httperver
import tornado.escape
import tornado.template
import os
 
class MainHandler(tornado.web.StaticFileHandler):
    def translate_path(self,path):
        path = path.split('?',1)[0]
        path = path.split('#',1)[0]
        path = os.path.normpath(tornado.escape.url_unescape(path))
        words = path.split('/')
        words = filter(None,words)
        path = os.getcwd()
        for word in words:
            drive, word = os.path.splitdrive(word)
            head, word = os.path.split(word)
            if word in (os.curdir,os.pardir):
                continue
            path = os.path.join(path,word)
        return path
 
    def list_directory(self,path):
        names = []
        for name in ['.','..']+os.listdir(path):
            fullname = os.path.join(path,name)
            displayname = linkname = name
            if os.path.isdir(fullname):
                displayname = name + '/'
                linkname = name + '/'
            if os.path.islink(fullname):
                displayname = name + '@'
            names.append((linkname,displayname))
        return names
 
    def get(self,path,include_body=True):
        path = self.translate_path(path)
        if not os.path.exists(path):
            raise tornado.web.HTTPError(404)
        if os.path.isdir(path):
            if not self.request.path.endswith('/'):
                self.redirect(self.request.path+'/')
                return
            names = self.list_directory(path)
            t = tornado.template.Template('''
                <html>
                    <head></head>
                    <body>
                        <h1>{{path}}</h1>
                        <hr/>
                        <ul>
                        {% for linkname,displayname in names %} 
                        <li><a href="{{linkname}}">{{displayname}}</a></li>
                        {% end %}
                        </ul>
                    </body>
                </html>
            ''')
            self.write(t.generate(names=names,path=path))
            return 
        super(MainHandler,self).get(path,include_body=True)
 
class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
                (r'/(.*)',MainHandler,{'path':'.'}),
                ]
        settings = {
                'template_path':os.path.join(os.path.dirname(__file__),'templates'),
                }
        tornado.web.Application.__init__(self,handlers,**settings)
 
 
def main():
    http_server = tornado.httperver.HTTPServer(Application())
    http_server.listen(8000)
    tornado.ioloop.IOLoop.instance().start()
 
if __name__ == '__main__':
    main()

原文链接: http://xiaoxins.com/archives/519

0     0

评价列表(0)

返回首页