Python development [Tornado]: Build a file download service, pythontornado
How to download Tornado files
Requirement: Enter the url address in the browser and prompt the download in the pop-up window.
Tornado server, set up file download service
#! /Usr/bin/env python #-*-coding: UTF-8-*-import tornado. ioloopimport tornado. webclass MainHandler (tornado. web. requestHandler): def get (self): filename = self. get_argument ('filename') # The http header browser automatically identifies itself as a file download. set_header ('content-type', 'application/octet-stream') # name of the file displayed during download self. set_header ('content-disposition', 'attachment; filename = % s' % filename) with open (filename, 'rb') as f: while True: data = f. read (1024) if not data: break self. write (data) # Remember to finish yourself. finish () def make_app (): return tornado. web. application ([(r "/", MainHandler),]) if _ name _ = "_ main _": app = make_app () app. listen (1, 8888) tornado. ioloop. IOLoop. current (). start ()
Enter the URL http: // 127.0.0.1: 8888/? For browser verification /? Filename=meeting_welcome.wav:
Supplement: In previous tests, the browser page displays a binary string. Later, it was found that the header type was not specified in the http package.