0

I'm writing a REST API. Users should be able to upload an image and view it. That part is easy, the images get saved to the media root, and serving them is handled separately by NGINX on /media/.

The problem is that the user needs to be able to generate a temporary link to their image. It can't be a simple redirect, because what's the point of a temporary link if the end user gets redirected to a permanent link?

Is there a way in Django to redirect the request on the backend, fetch the image, and return it to the user on the same URL? If not, what's the proper way to do it?

I've looked through Google for some 30 minutes, and couldn't find anything. I'm sorry if it's obvious and my search queries were just wrong.

Capyryan
  • 33
  • 3
  • 1
    You can create a url pattern with `` parameter, for example, and put a view behind this url that retrieves image path from db, image from MEDIA_ROOT and returns it (in a template or with `FileResponse`). – STerliakov Jun 15 '22 at 15:48
  • @SUTerliakov Ok, but how do I retrieve the image from MEDIA_ROOT to return it? What's the optimal way to do it? – Capyryan Jun 15 '22 at 16:46
  • I'd use just a model with `FileField` (or `ImageField`), then this field's `.path` attribute is filesystem location. You can add `SlugField` (or another field to use in short url) to that model and retrieve by it from view. – STerliakov Jun 15 '22 at 17:10

1 Answers1

0

I stumbled on a correct answer after searching some more random keywords related to this.

The correct answer is to use NGINX's X-Accel-Redirect feature. It seems like my search queries were indeed incorrect, the proper keyword was "protected media".

Here's a StackOverflow answer with a minimal solution: Django and Nginx X-accel-redirect

Capyryan
  • 33
  • 3