简体   繁体   中英

How to display image on web browser using Tornado Python server?

The error says the the indent is at the "if _name" etc. part.. I'm not sure why it would indicate this.

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()

try expects an except

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

in order to get it to show up as an image you will need to set the content header to reflect that it is an image mime-type ...

Where is the except block to match the get function? You should add, at a minimum, something like the following to the function.

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

if you have a separate folder for images and want to serve them as static content with a url eg

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

then you can make use of tornado.web.StaticFileHandler :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM