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

问题描述 投票:0回答:1

我目前正在从事一个涉及iCalendar文件的项目。在用户在我的网站上搜索他们的名字之后,我希望他们可以选择将显示的事件添加到他们的电话日历中。我以为可以做到的方式是创建一个.ics文件,当用户单击该文件时,该文件将根据用户名开始下载。

所以到目前为止,我所做的是一个Django视图,当按下“添加到日历”按钮时,将呈现该视图。然后,该视图将仅查询名称并获取其ics_string或日历数据。这是我到目前为止所写的视图

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

我所缺少的是如何将该文件发送以下载到客户端的计算机,而无需在服务器上创建它。我已经从Django库中使用io.StringIO和FileWrapeprs找到了一些答案,但是它们对我没有用。我找到的其他答案使用X-SendFile,但对我来说不起作用,因为它需要文件路径,并且我不希望在服务器上创建文件。

我目前正在使用Python 3.7.4 64位和Django 2.2.7版

python django icalendar
1个回答
0
投票

您可以指定媒体类型,并在响应中添加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
© www.soinside.com 2019 - 2024. All rights reserved.