【问题标题】:django Downloaded image file not storing in a temp filedjango 下载的图像文件未存储在临时文件中
【发布时间】:2014-07-05 15:19:57
【问题描述】:

我是 django 的新手。我有一个项目,用户可以在其中下载各种图像。我想跟踪下载的图像。这就是为什么我想将下载的图像文件存储在临时文件中。我已经创建了一个模型这个,下面给出..

 class Photo(models.Model):
    name = models.CharField(max_length = 100)
    photo = models.ImageField(upload_to = 'downloaded', blank=False,null=True)
    description = models.CharField(max_length = 80 , blank = False , null = True)
    user = models.ForeignKey(User)


    def __unicode__(self):
        return '%s %s %s'  %(self.description,self.name)

    def _get_image_url(self):
        return self.photo

和views.py

def download(request,image_id):
    filename = get_object_or_404(Photo,pk = image_id)
    filepath = filename.photo.url
    contributor = filename.user
    wrapper = FileWrapper(open(filepath,'rb',))
    content_type = mimetypes.guess_type(filepath)[0]
    response = HttpResponse(wrapper, mimetype='content_type')
    response['Content-Disposition'] = "attachment; filename=%s" % filepath
    if response and not filename.user==request.user:
                    purchased_image=PhotoDownload(name=filename.name,dowloaded_photo=filepath,user = request.user)
                    purchased_image.save()


    return response

根据给定的模型和视图,每当我下载任何图像时,都应该在 media 目录中创建一个 download 文件夹,不是吗?但是在下载任何图像后,没有在媒体目录中创建 download forlder,而是图像存储在数据库中,带有一个 url,就像这样......

http://med.finder-lbs.com/admin/photo/photodownload/2/media/media/photos/2_4.jpg

如果你仔细查看 url,你会发现图像存储在 /media/media/photos 应该存储在 media/photos 的位置,为什么会这样?我错过了什么还是有其他方法可以将下载的文件存储在临时文件夹中?我的其他照片,例如 上传的照片 存储在临时文件中,但下载的照片会导致问题。为了更方便,这里是 setting.py

import os
SETTINGS_DIR = os.path.dirname(__file__)
PROJECT_PATH = os.path.join(SETTINGS_DIR,os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
# Django settings for shutterstock project.



from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
    'django.core.context_processors.request',
)





DEBUG = True
TEMPLATE_DEBUG = DEBUG

#for Template path

TEMPLATE_PATH = os.path.join(PROJECT_PATH,'templates')

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
MEDIA_URL = '/media/' #GORKY >> This was media/

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''

STATIC_PATH = os.path.join(PROJECT_PATH,'static')
#STATIC_PATH = os.path.abspath(os.path.join(PROJECT_PATH, 'static'))

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
 STATIC_PATH,
)

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql',  'sqlite3' or 'oracle'.
         'NAME': 'stock',                      # Or path to database file if using sqlite3.
         # The following settings are not used with sqlite3:
         'USER': '',
         'PASSWORD': '',
         'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
         'PORT': '',                      # Set to empty string for default.
     }
 }


 ALLOWED_HOSTS = []


 TIME_ZONE = 'America/Chicago'


 LANGUAGE_CODE = 'en-us'

 SITE_ID = 1



 USE_I18N = True


 USE_L10N = True


 USE_TZ = True

 # Absolute filesystem path to the directory that will hold user-uploaded files.
 # Example: "/var/www/example.com/media/"


 # URL that handles the media served from MEDIA_ROOT. Make sure to use a
 # trailing slash.
 # Examples: "http://example.com/media/", "http://media.example.com/"


 # Absolute path to the directory static files should be collected to.
 # Don't put anything in this directory yourself; store your static files
 # in apps' "static/" subdirectories and in STATICFILES_DIRS.
 # Example: "/var/www/example.com/static/"


 # URL prefix for static files.


 # Additional locations of static files


 # List of finder classes that know how to find static files in
 # various locations.
 STATICFILES_FINDERS = (
     'django.contrib.staticfiles.finders.FileSystemFinder',
     'django.contrib.staticfiles.finders.AppDirectoriesFinder',
     'django.contrib.staticfiles.finders.DefaultStorageFinder',
 )

 # Make this unique, and don't share it with anybody.
 SECRET_KEY = '3zf@!cs!z(dsf3&6p93jrc6qz)-22n@uyps!5p*wkr3pxemy9e'

 # List of callables that know how to import templates from various sources.
 TEMPLATE_LOADERS = (
     'django.template.loaders.filesystem.Loader',
     'django.template.loaders.app_directories.Loader',
     'django.template.loaders.eggs.Loader',
 )
 TEMPLATE_DIRS = (TEMPLATE_PATH,)

 MIDDLEWARE_CLASSES = (
     'django.middleware.common.CommonMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     # Uncomment the next line for simple clickjacking protection:
     # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 )

 ROOT_URLCONF = 'shutterstock.urls'

 # Python dotted path to the WSGI application used by Django's runserver.
 WSGI_APPLICATION = 'shutterstock.wsgi.application'



INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',

    'photo',
    'userena',
    'guardian',
    'easy_thumbnails',
    'accounts',
    'cloudinary',
    'paypal.standard.ipn',
    'myprofile',
    'watermarker',
    'mail',
    'stored_messages',
    'rest_framework',
    'endless_pagination',
    'home',
    'easy_thumbnails',



  )

 MESSAGE_STORAGE = 'stored_messages.storage.PersistentStorage'

 WATERMARKING_QUALITY = 85
 WATERMARK_OBSCURE_ORIGINAL = False
 WATERMARK_OBSCURE_ORIGINAL = False

 AUTHENTICATION_BACKENDS = (  
    'userena.backends.UserenaAuthenticationBackend',  
    'guardian.backends.ObjectPermissionBackend',  
    'django.contrib.auth.backends.ModelBackend',  
)  

ANONYMOUS_USER_ID = -1

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'

AUTH_PROFILE_MODULE = 'accounts.MyProfile'  

LOGIN_REDIRECT_URL = '/accounts/%(username)s/'  
LOGIN_URL = '/accounts/signin/'  
LOGOUT_URL = '/accounts/signout/'  


LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
        'level': 'ERROR',
        'filters': ['require_debug_false'],
        'class': 'django.utils.log.AdminEmailHandler'
      }
   },
   'loggers': {
        'django.request': {
        'handlers': ['mail_admins'],
        'level': 'ERROR',
        'propagate': True,
        },
   }
}

THUMBNAIL_ALIASES = {
    '': {
       'mini': {'size': (50, 50), 'crop': True},
       'small': {'size': (100, 100), 'crop': True},
       'regular': {'size': (200, 200), 'crop': True},
       'large': {'size': (500, 500), 'crop': True},
       'xl': {'size': (800, 800), 'crop': True},
       'a4': {'size': (800, 600), 'crop': True},
       },
   }

那么你有什么想法吗?

【问题讨论】:

  • 将下载的图像保存到临时文件夹有什么意义?您在响应中将图像发送给用户。您已经拥有图像存储在服务器上,而您只是在浪费磁盘空间。此处是否要求能够跟踪用户何时下载图像?
  • 我只是忘了说主要目的,主要目的是,对下载的图像进行历史记录并显示给用户。

标签: python django image


【解决方案1】:

Image 的upload_to 属性告诉django 在上传文件时将文件存储在哪里,而不是下载文件。下载文件时存储文件是没有意义的......您不希望每次下载时都被相同文件的副本填充,不是吗?

如果您想维护请求日志,您可以将图像的 ID 或文件名存储在数据库中。您可以使用包含时间戳和一些日志信息的新模型来实现这一点。

【讨论】:

    【解决方案2】:

    跟踪下载

    要跟踪图像下载,您需要这样的东西:

    models.py:

    from django.contrib.auth.models import User
    
    class Photo(models.Model):
        photo = models.ImageField(upload_to = 'downloaded', blank=False,null=True)
        ...
    
    class Download(models.Model):
        photo = models.ForeignKey(Photo)
        user = models.ForeignKey(User, related_name='downloads')
        downloaded = models.DateTimeField(auto_now_add=True)
        # any other fields you want to store
    

    views.py:

    def download(request, photo_id):
        photo = get_object_or_404(Photo, pk=photo_id)
        download = Download(photo=photo, user=request.user)
        download.save()
        # serve file
    

    这会在数据库中为每个文件下载创建一条记录,显示下载的文件、下载该文件的用户以及下载的日期/时间。如果您没有登录用户,您可以存储其他内容,例如客户端 IP 地址。

    显示下载列表

    要显示当前用户的下载列表,您可以使用如下视图和模板:

    views.py:

    def my_downloads(request):
        downloads = request.user.downloads.all()
        return render(request, "my_downloads.html", {'downloads': downloads})
    

    my_downloads.html:

    ...
    <p>You've downloaded the following images:</p>
    <ul>
        {% for download in downloads %}
            <li>{{ download.photo.photo.name }}</li>
        {% endfor %}
    </ul>
    ...
    

    更多帮助

    关于您目前如何处理# serve file 位。您可能不直接在视图中提供文件。您可以简单地将请求重定向到文件的 url:

    from django.shortcuts import redirect
    
    def download(request, photo_id):
        ...
        return redirect(photo.photo.url)
    

    这意味着 Django 不必做实际发送文件的工作。

    【讨论】:

    • 我已经尝试过了,但问题是,我如何在模板中显示这些外键图像?
    • 你在模板上下文中给出photo.photo.url。您的模板试图显示什么?下载列表?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2016-12-22
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多