[FIXED] How to download a png file from url?

Hey guys, simple question. How do I download a png image into an object from a url?

I tried using the anvil built in HTTP methods, but I’m getting a strange error…
Here’s the method I constructed and called with a hardcoded url for testing purposes:

  def button_tree_click(self, **event_args):
    """This method is called when the button is clicked"""
    anvil.http.request('https://api.deepai.org/job-view-file/bc5bbb1c-7cbb-4f9a-a819-d448768b7816/outputs/output.png')

I’m getting an error message of

UnicodeDecodeError: invalid string at index 0 (possibly contains a unicode character)

I know the url is good, as I can download the picture manually by using my browser. I tried looking in the anvil docs and fourms to see if anybody had any similar issues. Thanks in advance.

Edit:

I was able to get some sort of result text for a png image by using the following methodology, but I’m not sure how to stuff it into a media object I can download. Here’s the method:

@anvil.server.callable
def png_request():
    r = requests.get('https://api.deepai.org/job-view-file/7ebf2d7d-a5b5-408f-a1a2-641b8234bd8a/outputs/output.png')
    c = r.content
    print(c)

Hi @nathanguyette,

Oops! Looks like you’ve found a bug in our client-side anvil.http.request(), so I’ve moved this to Bug Requests. You’re using anvil.http.request().

We’ll be deploying a fix in the New Year; in the meantime, you can do the request on the server, and return the Media object to the client, like so:

@anvil.server.callable
def png_request():
    return anvil.http.request('https://api.deepai.org/job-view-file/7ebf2d7d-a5b5-408f-a1a2-641b8234bd8a/outputs/output.png')

So now you can call:

my_png = anvil.server.call("png_request")
# ... do whatever you want with the PNG - display it on an
# Image component, download it with download(), etc.
1 Like

Sorry… I’m probably doing something wrong here but I’m now getting this error when trying to run the workaround you gave me for the png_request() method.

AttributeError: module 'anvil' has no attribute 'http'

My server module imports look like:

import anvil.tables as tables
import anvil.tables.query as q
from anvil.tables import app_tables
import anvil.server
import requests

Make sure you do import anvil.http In your server module.

1 Like

@stucork, thanks! that was it.