mike
mike

Reputation: 907

how to give a name to downloaded file with async tornado client

i have some python tornado code that i use to get files async

from tornado import ioloop , httpclient
def get_file(url):
    http_client = httpclient.AsyncHTTPClient()
    http_client.fetch(url,done)

def done()
    print "Done"
url = "http://localhost/files/ldfhgdksgfjkdfadf/output.pdf"
ioloop.IOLoop.instance().start()

what happens is that the file gets saved in the current dir as "output.pdf", is there any way with asynchttp client to specify a file name? if i could i would call the file by some name and save it in a different directory other than the current directory.

Upvotes: 1

Views: 1634

Answers (1)

alecxe
alecxe

Reputation: 473873

What about reading response.body in the specified callback and write it to the appropriate file, e.g.:

from tornado import ioloop, httpclient


def get_file(url):
    http_client = httpclient.AsyncHTTPClient()
    http_client.fetch(url, callback=done)


def done(response):
    with open("my_favorite_directory/my_favorite_filename.pdf", "w") as f:
        f.write(response.body)
    print "DONE"


get_file("http://samplepdf.com/sample.pdf")
ioloop.IOLoop.instance().start()

Upvotes: 2

Related Questions