您可以定期运行一个任务,tornado.ioloop.PeriodicCallback
用于创建将视频映射到类别的字典:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
videos = {}
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html', my_videos=videos)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler),
]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=True,
)
tornado.web.Application.__init__(self, handlers, **settings)
def update_categories(self):
videos.clear()
for path, subdirs, files in os.walk(self.settings['static_path'] + '/videos/'):
category_name = os.path.basename(path)
videos[category_name] = []
for name in files:
videos[category_name].append(name)
if __name__ == "__main__":
tornado.options.parse_command_line()
app = Application()
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.PeriodicCallback(app.update_categories, 1000).start() # run every second
tornado.ioloop.IOLoop.instance().start()
我使用子目录名称作为类别名称。项目树:
$ tree
.
├── static
│ └── videos
│ ├── cat1
│ │ ├── vid1.avi
│ │ └── vid2.avi
│ ├── cat2
│ │ ├── vid3.avi
│ └── Empty category
├── templates
│ ├── index.html
└── test.py
我正在使用这个模板:
<!-- index.html -->
<html>
<head>
<title>Test</title>
</head>
<body>
{% for category in my_videos %}
<h1>{{category}}</h1>
{% for video in my_videos[category] %}
<p>{{video}} -> {{static_url("videos/")}}{{category}}/{{video}}</p>
{% end %}
{% end %}
</body>
</html>
它打印所有视频。您还可以在处理程序中从字典中选择一个视频并进行处理。
这种方法有点重,因为文件系统是定期遍历的。最好在添加新内容时通知应用程序。