Skip to content

Instantly share code, notes, and snippets.

@daimon99
Last active May 9, 2019 11:02
Show Gist options
  • Save daimon99/76c278290b47fe355e37decf76808bca to your computer and use it in GitHub Desktop.
Save daimon99/76c278290b47fe355e37decf76808bca to your computer and use it in GitHub Desktop.
下载签权逻辑设计
server {
listen 80;
server_name xxx;
access_log /xxx/logs/dapi.access.log main;
error_log /xxx/logs/dapi.error.log warn;
root /xxx/dapi/www/;
client_max_body_size 20m;
gzip on;
gzip_min_length 4k;
gzip_comp_level 6;
gzip_types text/plain application/x-javascript text/css application/xml application/javascript application/json;
gzip_vary on;
gzip_http_version 1.1;
location @django {
proxy_pass http://127.0.0.1:9601;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header Cache-Control no-store;
}
location / {
try_files $uri $uri/ @django;
}
location /static {
alias /xxx/dapi/staticfiles;
}
location /internal {
internal;
alias /xxx/dapi/uploads;
}
}
@api_view(['GET'])
@permission_classes(())
def download(request: Request, file_path: str):
ranges = request.META.get('HTTP_RANGE')
if utils.is_md5(file_path):
file_path = file_path.strip(' /').lower()
file_obj: m.ShareStorage = m.ShareStorage.objects.filter(file_md5=file_path).first()
if file_obj:
file_path = file_obj.file.name
else:
file_obj: m.ShareStorage = m.ShareStorage.objects.filter(file__exact=file_path).first()
if file_obj:
full_path = file_obj.file.path
response = HttpResponse(content_type='application/octet-stream;charset=utf-8;')
file_name = file_obj.file_name if file_obj.file_name else os.path.basename(file_obj.file.name)
log.info('file_name: %s', file_name)
file_mime = mimetypes.guess_type(file_name)
response['X-Accel-Redirect'] = f'/internal/{urllib.parse.quote(file_path)}'
response['Content-Type'] = file_mime[0]
if file_mime[0] is None:
response['Content-Disposition'] = 'attachment; filename=' + urllib.parse.quote(file_name)
else:
response['Content-Disposition'] = 'filename=' + urllib.parse.quote(file_name)
log.info('download file: [%s] %s', file_mime[0], full_path)
if ranges is None or 'bytes=0' in ranges:
# 首次观看的计数
m.ShareStorage.objects.filter(pk=file_obj.pk).update(download_count=F('download_count') + 1)
else:
log.info('ranges: %s', ranges)
return response
else:
log.warning('download file not exist: %s', file_path)
return HttpResponse('文件不存在', status=404)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment