简体   繁体   English

如何动态提供文件,然后使它们可在 Django 中下载?

[英]How can I dynamically serve files and then make them downloadable in Django?

I'm currently working on a project that deals a lot with iCalendar files.我目前正在处理一个处理大量 iCalendar 文件的项目。 Where after the user searches for their name on my website I would like to have an option for them to add the events shown to their phone calendars.在用户在我的网站上搜索他们的名字后,我希望他们可以选择将显示的事件添加到他们的电话日历中。 The way I imagined that could be done is by creating a .ics file and when users click it the file would begin downloading based on the name of the user.我想象的方法是创建一个 .ics 文件,当用户单击它时,该文件将根据用户名开始下载。

So what I have made so far is a Django view that that when the "Add to Calendar" button is pressed, the view is rendered.所以到目前为止我所做的是一个 Django 视图,当按下“添加到日历”按钮时,视图被呈现。 The view would then just get the name queried and get its ics_string or the calendar data.然后视图将只获取查询的名称并获取其 ics_string 或日历数据。 Here is the view that i've written so far这是我到目前为止所写的观点

def serve_calendar(request):
    name = request.GET.get('name', '')
    ics_string = get_calendar_details(name)

    #the portion of code that i can't figure out

    return response

What I am missing is how do I send this file for download to the client's machine without the need to create it on the server.我缺少的是如何将要下载的文件发送到客户端的计算机,而无需在服务器上创建它。 I've found some answers using io.StringIO and FileWrapeprs from the Django library however they have not worked for me.我从 Django 库中使用 io.StringIO 和 FileWrapeprs 找到了一些答案,但是它们对我不起作用。 Other answers I've found use the X-SendFile but that would not work for me as it requires a path to a file and I don't want the file to be created on the server.我发现其他答案使用 X-SendFile 但这对我不起作用,因为它需要文件的路径,而且我不希望在服务器上创建该文件。

I'm currently using Python 3.7.4 64-bit with Django version 2.2.7我目前正在使用 Python 3.7.4 64 位和 Django 版本 2.2.7

You can specify the media type, and add a Content-Disposition header om the response:您可以指定媒体类型,并在响应中添加一个Content-Disposition标头:

from django.http import HttpResponse

def serve_calendar(request):
    name = request.GET.get('name', '')
    ics_string = get_calendar_details(name)
    response = HttpResponse(ics_string, content_type='text/calendar')
    response['Content-Disposition'] = 'attachment; filename=calendar.ics'
    return response

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM