Django 下载 JSON 文件接口实现 - 避免浏览器打开直接下载
在 Django 中,可以使用 HttpResponse 对象将 JSON 数据作为附件下载。以下是实现下载 JSON 文件接口的示例代码:
import json
from django.http import HttpResponse
def download_json(request):
data = {'key1': 'value1', 'key2': 'value2'}
json_data = json.dumps(data)
response = HttpResponse(json_data, content_type='application/json')
response['Content-Disposition'] = 'attachment; filename='data.json''
return response
在上面的代码中,我们首先创建一个字典对象,将其转换为 JSON 格式并将其存储在变量 json_data 中。然后,我们使用 HttpResponse 对象将 JSON 数据作为附件下载。我们设置 response 的 content_type 为 'application/json',这将告诉浏览器返回的内容是 JSON 格式的数据。我们还设置 response 的 Content-Disposition 头部,以指定文件名为 'data.json' 并将其作为附件下载。
在视图函数中调用 download_json 函数即可下载 JSON 文件:
def my_view(request):
# ...
return download_json(request)
原文地址: https://www.cveoy.top/t/topic/opkT 著作权归作者所有。请勿转载和采集!