gpt4 book ai didi

python - 如何通过保护只有经过身份验证的用户才能看到的 url 来使文件私有(private)

转载 作者:太空狗 更新时间:2023-10-29 18:28:52 24 4
gpt4 key购买 nike

我想知道是否有一种方法可以保护图像或文件在未经身份验证时隐藏起来。

假设我的网站上有一张图片,只有在该用户通过身份验证后才能看到。但问题是我可以复制网址或在新标签页中打开图片。

http://siteis.com/media/uploaded_files/1421499811_82_Chrysanthemum.jpg

再一次,即使我没有经过身份验证,我也可以通过转到该 url 查看该特定图像。所以,我的问题是,如何保护文件,以便只有经过身份验证的用户才能看到?

更新:

查看:

def pictures(request, user_id):
user = User.objects.get(id=user_id)
all = user.photo_set.all()
return render(request, 'pictures.html',{
'pictures': all
})

模型:

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

class Photo(models.Model):
photo_privacy = models.CharField(max_length=1,choices=PRIVACY, default='F')
user = models.ForeignKey(User)
image = models.ImageField(upload_to=get_upload_file_name)

设置:

if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "myproject", "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "myproject", "static", "media")
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "myproject", "static", "static"),
)

更新:

模板:

{% if pictures %}
{% for photo in pictures %}
<img src="/media/{{ photo.image }}" width="300" alt="{{ photo.caption }}"/>
{% endfor %}
{% else %}
<p>You have no picture</p>
{% endif %}

网址:

url(r'^(?P<user_name>[\w@%.]+)/photos/$', 'pictures.views.photos', name='photos'),

if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

最佳答案

通过保护任何媒体文件不被匿名用户提供,更好的 url 保护方式。

代码(更新):

from django.conf.urls import patterns, include, url
from django.contrib.auth.decorators import login_required
from django.views.static import serve
from django.conf import settings

from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import HttpResponse

@login_required
def protected_serve(request, path, document_root=None):
try:
obj = Photobox.objects.get(user=request.user.id)
obj_image_url = obj.image.url
correct_image_url = obj_image_url.replace("/media/", "")
if correct_image_url == path:
return serve(request, path, document_root)
except ObjectDoesNotExist:
return HttpResponse("Sorry you don't have permission to access this file")


url(r'^{}(?P<path>.*)$'.format(settings.MEDIA_URL[1:]), protected_serve, {'file_root': settings.MEDIA_ROOT}),

注意:以前任何登录用户都可以访问任何页面,现在此更新限制非用户查看其他文件......

关于python - 如何通过保护只有经过身份验证的用户才能看到的 url 来使文件私有(private),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28007770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com