如何通过Tornado Python服务器在网页上显示图片?

0 投票
3 回答
3352 浏览
提问于 2025-04-18 14:21

这个错误提示说问题出在“if _name”这一部分。我不太明白为什么会指向这里。

class GetFileHandler(tornado.web.RequestHandler):
    def get(self):

        fileid = self.get_argument('fileid', "")

        cur.execute("""SELECT filepath FROM files_table WHERE file_id = %s""", (fileid, ))
        m = cur.fetchall()
        y = m[0]
        x = y[0]

        path = x + "/" + fileid + ".jpg"

        try:
            with open(path, 'rb') as f:
                data = f.read()
                self.write(data)
            self.finish()
if __name__ == "__main__": 
    tornado.options.parse_command_line() 
    app = tornado.web.Application(handlers=[(r"/getit", GetFileHandler)])
    http_server = tornado.httpserver.HTTPServer(app) 
    http_server.listen(options.port) 
    tornado.ioloop.IOLoop.instance().start()

3 个回答

0

如果你有一个单独的文件夹专门用来存放图片,并且想通过一个网址来访问这些图片,比如说:

http://yourwebsite.com/images/yourimage.jpg

那么你可以使用 tornado.web.StaticFileHandler 来实现这个功能:

handlers = [
        (r"/images/(.*)", tornado.web.StaticFileHandler, {'path': "./images"}),
        (r"/", WebHandler)
]
0

在这个函数里,哪里有用来处理错误的except块呢?你至少应该添加一些类似下面的内容到这个函数里。

except IOError as xcpt:
    # IO error handling
    raise xcpt  # if you want to propagate the exception
3

try 需要配合 except 使用

try:
    with open(path, 'rb') as f:
        data = f.read()
        self.write(data)
    self.finish()
except IOError:
    print "Failed!!"

为了让它显示为图片,你需要设置内容头,让它表明这是一个图片类型...

撰写回答