Anvil Media URL - not permanent

In short:
Is there a way to generate a URL for a media object in an anvil table that is permanent and can be shared?

What I’m trying to do:
Hi there,
I’m building a test integration with the PWINTY API that let’s you do print-on-demand for several products.

I have an anvil table with a Media column that stores an Image, and I’m calling the [image].get_url() method to generate a url which I then pass onto the pwinty api.

However, I am having issues because it seems that every time I call this method, I get a different URL - and the old URL is discarded. Due to the latency between when I send the request and when the order is processed on pwinty’s end - this causes an issue in fetching the image.

Is there a way to generate a URL for a media object in an anvil table that is permanent and can be shared?

Thanks,
pat

Anvil doesn’t give you permanent URLs to media objects, you have to build that functionality into an HTTP endpoint that serves the media object. So you might build an HTTP endpoint that takes a query parameter saying which media you want, and in the endpoint you’ll do the data table search to fetch the media object and return it.

I’ve never done that myself, but hopefully someone else who has can give you more details.

3 Likes

This did the trick, thank you!

For anyone interested in a solution.

Here is the HTTP endpoint that serves the image for a given id:

@anvil.server.http_endpoint('/images/:id')
def get_image(id):
    print(f"Request was made for image with id {id}")
    image_row = app_tables.images.get_by_id(id)
    image = image_row['Image']
    return image

And to generate the URL that serves said image:

CLIENT

def get_image_url(self, image_row):
    self.image_url = anvil.server.call('get_image_url_from_id', image_row.get_id())
    return self.image_url

SERVER

@anvil.server.callable()
def get_image_url_from_id(id):
    return f"{anvil.server.get_api_origin()}/images/{id}"

You can combine the above two but in my case it made sense to have the url be generated on the client-side.

Hope this helps

2 Likes