python - 我可以使用 Django 来防止直接访问图像文件吗?

标签 python django

我想阻止我的网络用户简单地右键单击图像并复制/共享 URL。某些经过身份验证的用户可以访问某些图像,我想尽可能地强制执行此操作。未经身份验证的用户不应访问图像文件。

根据我的阅读,由于性能问题,通常建议避免从数据库存储/获取图像。

我考虑过使用 Django View 函数读取文件(服务器端,在 python 中)并将其插入网页(可能是 base64 编码,或其他方式)的函数。结合拒绝外部请求的 .htaccess 文件,这可能会起作用,但它似乎会占用大量资源。

是否有任何其他选项来执行此规则?我知道用户可以截屏、保存图像等,但我有责任尽可能地执行这些限制,我最好的选择是什么?

编辑:我没有使用 CDN 的经验,但如果它是满足这些需求的可行选择,我愿意使用它。

最佳答案

我会咬人的。

session 中间件 - 不优雅,但可以工作

您不希望公开提供的图像不通过标准的 apache/django 静态文件配置提供。

然后您的 session 中间件可以检查所有传入的路径请求,如果路径是您的图像目录(例如/privateimg/)并且用户未通过身份验证,您可以将它们退回或将其替换为另一个图像(例如带有水印的)。

您可以查看有关 session 中间件如何工作的 django 文档 https://docs.djangoproject.com/en/dev/topics/http/sessions/

人们仍然可以传递你的链接,但只有经过身份验证的用户才能真正看到所述链接的内容(称为门控你的内容)

详细说明:

设置.py

GATED_CONTENT = (
    '/some_content_dir/', # This is a directory we want to gate
    '.pdf', # maybe we want to gate an entire content type
)

MIDDLEWARE_CLASSES = (
    ...  # Out of the box middleware...blah blah
    'yourapp.somemodule.sessionmiddleware.GatedContent',
)

然后你有以下应用程序结构

yourapp
   |-somemodule
        |-sessionmiddleware.py

现在开始吃肉(好吃!)

session 中间件.py

class GatedContent(object):
"""
Prevents specific content directories and types 
from being exposed to non-authenticated users
"""

def process_request(self, request):
   path = request.path
   user = request.user # out of the box auth, YMMV

   is_gated = False
   for gated in settings.GATED_CONTENT:
      if path.startswith(gated) or path.endswith(gated):
          is_gated = True
          break
  # Validate the user is an authenticated/valid user
  if is_gated and not user.is_authenticated():
      # Handle redirect

 

关于python - 我可以使用 Django 来防止直接访问图像文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20555023/

相关文章:

python - 事件 virtualenv 不工作

css - 使用 Django ModelForm 时标记必填字段的标签

python - 如何将虚拟环境从服务器复制/克隆到本地计算机

python - 如何检查正在执行的 Python 脚本的哪一行?

python - 错误从 groupby 中的重复轴重新索引

python - 属性错误 : 'RandomForestClassifier' object has no attribute 'fit_transform'

python - 如何将类中的函数应用到 Pandas Dataframe 中

django - Komodo Edit 5.2 Django 模板语法错误 - 信息 : <head> previously mentioned

python - 动态模板标签

python - Cython OpenMP 编译器标志