0

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

在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

当我单击链接或转到链接时,我运行此方法的错误:

No results - Empty KML file

我认为这是因为 filename= 和保存的 final 不同。

4

1 回答 1

1

对于simplekml模块,有一个函数可以将 kml 作为字符串而不是另存为文件,因此首先从 kml 字符串初始化响应并返回 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
于 2016-12-14T16:50:17.430 回答