Domanda

From what I read, static files should be served directly by the server instead of using Python and Django. But I need to restrict access of files to the users who uploaded them. Unfortunately, the documentation doesn't have a section on serving static files uploaded by a user in production environments.

If I'm right, Facebook uses long urls that are hard to guess. This sounds like a reasonable approach to me. How can I automatically generate long ids and use them for uploaded media files in Django?

È stato utile?

Soluzione

You can make use of slugify and datetime.

from django.template.defaultfilters import slugify
import datetime

class MyModel(models.Model):
    title = models.CharField(max_length=150, db_index=True)
    image = models.Charfield(max_length=150, unique=True)
    ....
    ....
    def save(self):
        super(MyModel, self).save()
        date = datetime.date.today()
        self.image = '%i/%i/%i/%s' % (
            date.year, date.month, date.day, slugify(self.title)
        )
        super(MyModel, self).save()

Or just

Using time

from time import time

def get_upload_file_name(instance, filename):
    return "uploaded_files/%s_%s" %(str(time()).replace('.','_'), filename)

class MyModel(models.Model):
    description = models.TextField()
    image = models.ImageField(upload_to=get_upload_file_name)

    def __unicode__(self):
        return "%s --> %s" % (self.user, self.description)

Or

By using this module - django-unique-random

Hope it helps!

Altri suggerimenti

If you want to do this the proper way, you should use the X-SendFile/X-Accel-Redirect header in web servers that supports them (Apache, NGinx, maybe more). You may need to enable modules on the web servers (e.g. mod_xsendfile in Apache).

What the X-SendFile does is that it instructs the front-end web server to replace the body of the response with the file mentioned in the X-SendFile header. This way you can have your Django application check for the file's access permission while offloading the servicing of the file download to the front-end server.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top