【问题标题】:Creating a file and returning it to Django in a view创建文件并在视图中将其返回给 Django
【发布时间】:2016-12-14 16:31:38
【问题描述】:

我正在尝试动态构建一个 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 不是同一个。

【问题讨论】:

    标签: python django django-views kml simplekml


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2014-07-22
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      • 2013-08-07
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多