在提供文件Nginx Django的同时使用UUID缩短URL [英] URL shortening using UUID while serving files nginx django

查看:53
本文介绍了在提供文件Nginx Django的同时使用UUID缩短URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Django2和nginx,用户可以上传文件(主要是pic,vids),而我想通过屏蔽完整的网址路径来提供这些文件.

Using Django2 and nginx, users can upload files (mainly pic,vids) and I want to serve those files by masking the full url path.

这是我希望看到的示例结构,但我不想让用户知道此结构甚至图像文件名.

This is the example structure I expect to see but I don't want users to know about this structure or even the image filename.

domain.com/media/user/pictures/Y/M/D/image1.jpg

我希望用户通过这样的url看到上面的图像,并且每个文件的随机UUID编号都会发生变化,并且该编号可以指向任何类型的文件.

I want the user to see the above image through a url like this and the random UUID number changes for each file and that number can point to any type of file.

domain.com/media/23kj23l9ak3

上传文件时,原始名称,分配的权限(公共,朋友,私人),文件路径和生成的UUID存储在数据库中),但文件存储在文件系统或远程位置.

When the file is uploaded the original name, permissions assigned (public, friends, private), file path and the UUID that is generated stored in the database) but the file is stored on the filesystem or remote location.

我以前从未接触过这一点,我想知道现代的实现方式,或者让我知道django/nginx的哪些技术/功能可以帮助我解决它.

I've never got to this point before and I would like to know what the modern way of doing it would be or let me know what technology/features of django/nginx can help me solve it.

推荐答案

我不完全确定为什么要这样做,而不是简单地将UUID用作上载文件的文件名,但是您当然可以做到这一点

I'm not entirely sure why you want to do this, rather than simply using the UUID as the filename of the uploaded file, but you certainly can do it.

一种好方法是通过Django路由请求,并使用自定义的X-Accel-Redirect标头告诉nginx使用特定文件进行响应.您将需要将UID和实际路径存储在Django模型中.因此,nginx的配置将类似于:

One good way would be to route the request via Django, and use the custom X-Accel-Redirect header to tell nginx to respond with a specific file. You would need to store both the UID and the actual path in a Django model. So the nginx config would be something like:

location /protected/ {
  internal;
  alias   /media/user/; # note the trailing slash
}

和Django视图将是:

and the Django view would be:

def user_picture(request, uuid):
    image = MyModel.objects.get(uuid=uuid)
    response = HttpResponse(status=200)
    response['X-Accel-Redirect'] = '/protected/' + image.file.path
    return response

这篇关于在提供文件Nginx Django的同时使用UUID缩短URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆