创建文件并在视图中将其返回给 Django

Creating a file and returning it to Django in a view

我正在尝试动态构建 KML 文件供用户下载。我正在使用 python 中的 KML 库来生成和保存 KML,但我想 return 该文件作为广告下载。本质上,如果我的应用程序中的用户单击 link bam,KML 将由用户单击 link 生成并下载。我的代码不起作用,我猜我的响应设置不正确:

在views.py中:

def buildKML(request):
    # Create the HttpResponse object with the appropriate PDF headers.

    response = HttpResponse(content_type='application/kml')
    response['Content-Disposition'] = 'attachment; filename="botanicalgarden.kml"'
    #just testing the simplekml library for now
    kml = simplekml.Kml()
    kml.newpoint(name="Kirstenbosch", coords=[(18.432314,-33.988862)])  # lon, lat, optional height
    kml.save('botanicalgarden.kml')

    return response

当我单击 link 或转到 link 时,此方法出现 运行 错误:

No results - Empty KML file

我猜是因为filename=和保存的final不是一个。

对于 simplekml 模块,有一个函数可以将 kml 获取为字符串而不是保存为文件,因此首先初始化来自 kml 字符串和 return HttpResponse 对象

的响应
kml = simplekml.Kml()
kml.newpoint(name="Kirstenbosch", coords=[(18.432314,-33.988862)])
response = HttpResponse(kml.kml())
response['Content-Disposition'] = 'attachment; filename="botanicalgarden.kml"'
response['Content-Type'] = 'application/kml'
return response