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

时间:2016-12-14 16:31:39

标签: python django django-views kml

我正在尝试构建一个KML文件,供用户下载。我在python中使用KML库来生成和保存KML,但我想将文件作为ad ownload返回。基本上,如果我的应用程序中的用户单击链接bam,则用户单击该链接会生成并下载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不是同一个。

1 个答案:

答案 0 :(得分: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