Downloading File from url

Hi everyone,

I am facing some issues with downloading file from URL, which might seem as repeatable question and trivial. However, I tried the suggested solutions from previous posts and I haven’t managed to make them work for me. My data is hosted in virtual drive (dropbox) and I managed to retrieve the link for the hosted files. But, when I try to convert the URL to media object, I receive an error saying can’t connect to dropbox. For this particular case, I tried the following code:

my_media_obj2=anvil.URLMedia(‘url generated from dropbox where file is located’)
anvil.media.download(my_media_obj2)

I also trierd to convert the url to Blobmedia:

 my_media_obj2=anvil.URLMedia('url')

new = anvil.BlobMedia('application/octet-stream',my_media_obj2.get_bytes(),name='new_name.file')
anvil.media.download(new)

I Tried the requests approach as well as using dropbox api method in downloading files, by creating a function inside anvil server. However, both attempts were also unsuccessful. Even though when I tried them both using Jupiter, I was able to download the file with no issue.

using requests:

def download_file(url,filename=''):
try:
    if filename:
        pass
    else:
        filename=req.url[downloadurl.rfind('/')+1:]
        
    with requests.get(url) as req:
        with open(filename, 'wb') as f:
            for chunk in req.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
            return filename
except Exception as e:
    print(e)
    
    return None 

Dropbox api method to downlaod file:

import dropbox
dbx = dropbox.Dropbox("access token")
with open("test_experimet1.xlsx", "wb") as f:
metadata, res = dbx.files_download(path="/Mariner_cost.xlsx")
f.write(res.content)

Any ideas on how to overcome this issue?

Many thanks.

Can you post a full copy of the errors that you are receiving? Did you copy the exact same code from Jupyter?

I don’t know the Dropbox package but if I t is saying access denied, have you checked that the access token is correct? Currently you are passing it a string “access_token”. Is this meant to be a variable instead?

@rickhurlbattThanks for commenting on my post. The problem lies with converting the url to media objects, and you can even ignore the part of downloading the file from my post. Also, the file format is not typical file like xlsx or txt and so forth. On the method that you are referring to in your post, I replaced the access token with the actual string from dropbox, no issues with connection. I was able to use dropbox and read excel files using pandas.

When I use the first method, I had reply of dropbox lost the connection. I haven’t tried google drive, which seems as potential solution, but was hoping of accomplishing my goal of converting the files to media objects from dropbox instead, as I already have a business account.