Django:在通用视图中提供下载 [英] Django: Serving a Download in a Generic View

查看:74
本文介绍了Django:在通用视图中提供下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想从 / home / username / music 中的文件夹中提供几个mp3。我不认为这会是一个这么大的事情,但我有点困惑如何使用通用视图和我自己的url。

So I want to serve a couple of mp3s from a folder in /home/username/music. I didn't think this would be such a big deal but I am a bit confused on how to do it using generic views and my own url.

urls.py

url(r'^song/(?P<song_id>\d+)/download/$', song_download, name='song_download'),

我正在关注的示例在Django文档的通用视图部分:
http://docs.djangoproject.com/en/ dev / topics / generic-views / (这一切都在底部)

The example I am following is found in the generic view section of the Django documentations: http://docs.djangoproject.com/en/dev/topics/generic-views/ (It's all the way at the bottom)

我不是100%肯定如何根据需要量身定做。这是我的views.py

I am not 100% sure on how to tailor this to my needs. Here is my views.py

def song_download(request, song_id):
    song = Song.objects.get(id=song_id)

    response = object_detail(
        request,
        object_id = song_id,
        mimetype = "audio/mpeg",
    )
    response['Content-Disposition'= "attachment; filename=%s - %s.mp3" % (song.artist, song.title)

    return response

我实际上是失去了如何传达,我想要它吐出我的mp3,而不是现在做什么输出一个.mp3与所有当前页面html包含。我的模板应该是我的mp3吗?我需要设置apache来提供这些文件,还是Django能够从文件系统中获取mp3(当然是适当的权限),并提供这些?如果确实需要配置Apache,我该如何告诉Django?

I am actually at a loss of how to convey that I want it to spit out my mp3 instead of what it does now which is to output a .mp3 with all of the current pages html contained. Should my template be my mp3? Do I need to setup apache to serve the files or is Django able to retrieve the mp3 from the filesystem(proper permissions of course) and serve that? If it do need to configure Apache how do I tell Django that?

提前感谢。这些文件都在HD上,所以我不需要现场生成任何东西,如果可能的话,我想防止这些文件的位置泄露。一个简单/歌曲/ 1234 /下载将是太棒了。

Thanks in advance. These files are all on the HD so I don't need to "generate" anything on the spot and I'd like to prevent revealing the location of these files if at all possible. A simple /song/1234/download would be fantastic.

推荐答案

为什么要使用通用视图?在没有通用视图的情况下很容易做到这一点:

Why do you want to do this with a generic view? It's very easy to do this without generic views:

def song_download(request, song_id):
    song = Song.objects.get(id=song_id)
    fsock = open('/path/to/file.mp3', 'r')
    response = HttpResponse(fsock, mimetype='audio/mpeg')
    response['Content-Disposition'] = "attachment; filename=%s - %s.mp3" % \
                                     (song.artist, song.title)
    return response

我不知道是否可以通过一般的视图使这项工作不知所措。但是无论哪种方式,使用一个都是冗余的。没有要渲染的模板,通用视图自动提供的上下文是无用的。

I'm not sure if it's possible to make this work somehow with a generic view. But either way, using one is redundant here. With no template to render, the context that is automatically provided by the generic view is useless.

这篇关于Django:在通用视图中提供下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆