0

我有大约 5 个类别的视频,每个类别都有几个小时的视频文件会话,我想使用龙卷风将所有这些提供给最终用户,为他们提供他们请求的视频,获得的最佳方式是什么这完成了吗?(我想要一种自动生成 url 的方法,因为服务器可以只观看放置/添加视频的某个目录,并自动将视频添加到相应的类别菜单/创建新类别,这也意味着我避免使用处理程序每个类别)。我在想什么可能吗?

class VideoHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("relevant-video") # serve correct video maybe suing the incoming url?

settings = {'static_path': os.path.join(PATH, 'static')}

handlers = [(r'/videos', VideoHandler),
            (r'/favicon.ico', tornado.web.StaticFileHandler, {'path': favicon_path})]
4

1 回答 1

1

您可以定期运行一个任务,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>

它打印所有视频。您还可以在处理程序中从字典中选择一个视频并进行处理。

这种方法有点重,因为文件系统是定期遍历的。最好在添加新内容时通知应用程序。

于 2013-06-08T07:04:42.040 回答