简体   繁体   中英

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. 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.

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. The view would then just get the name queried and get its ics_string or the calendar data. 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. 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.

I'm currently using Python 3.7.4 64-bit with Django version 2.2.7

You can specify the media type, and add a Content-Disposition header om the response:

from django.http import HttpResponse

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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