[SOLVED] How do I return a file download by a function?

Issue

Before the post I just wanted to premise 2 things:

  1. I’m into programming from less than a month so any enhancement, alternatives, precisations or excesses in explanations, is Boldy appreciated.
  2. It’s my first post on Stack Overflow, hope I structured it correctly.

So I was trying to define a function "download(url)" that should download a file with a progress bar from a url given as whatever "url" is called in the function i just created.

I made it look like this:

def download(url):
    import requests
    from progress.bar import Bar
    
    file = requests.get(url, stream=True)
    dictdata = eval(str(file.headers))
    total_length = dictdata["Content-Length"]
    with Bar("Downloading...") as bar:
        for chunk in file.iter_content(chunk_size=(int((int(total_length))/100))):
                <Here goes something that writes it down to a variable or something like 
                that but I don't know how that's called yet.> 
                bar.next()
    return <the variable or whatever it'll be.>

I expect it to work like this by the way:

file = download(example)

So how do I do this?

Solution

Maybe you want to store the chunk of bytes?

data = bytearray()
with Bar("Downloading...") as bar:
    for chunk in file.iter_content(chunk_size=(int((int(total_length))/100))):
        data += chunk
        bar.next()
return data

Answered By – nosklo

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published.