无法从Django发送HttpResponse

16 浏览
0 Comments

无法从Django发送HttpResponse

我试图将带有附加头信息的JSON格式转换成以.csv格式下载到前端。

在发送HTTP响应时,我遇到了“is not JSON serializable”错误。

我的views.py文件:

from datetime import datetime
from django.shortcuts import render
from django.http import HttpResponse
import json as simplejson
import random
import csv
def DownloadEventLog(request):
    downloadeventlog = "[{\"severity\":\"0\",\"description\":\"USB Connected\",\"date\":\"01/01/2015\",\"time\":\"11:35:20\"},{\"severity\":\"3\",\"description\":\"USB Disconnected\",\"date\":\"01/01/2015\",\"time\":\"10:30:19\"}]";
    data = simplejson.loads(downloadeventlog)
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="eventlog.csv"'
    writer = csv.writer(response)
    writer.writerow(data[0].keys())
    for row in data:
        writer.writerow(row.values())
    print response
    return HttpResponse(simplejson.dumps(response), content_type = "application/json")

Print response cmd is printing:

Content-Type: text/csv
Content-Disposition: attachment; filename="eventlog.csv"
date,time,severity,description
01/01/2015,11:35:20,0,"USB Connected"
02/02/2015,10:30:19,3,"USB Disconnected"

然而,最后一行出现了以下错误:

TypeError at /eventlog/downloadeventlog
is not JSON serializable
Request Method: POST
Request URL: http://127.0.0.1:8001/eventlog/downloadeventlog
Django Version: 1.7.1
Python Version: 2.7.3

0
0 Comments

在Django中无法发送HttpResponse的问题通常是由于不正确地使用HttpResponse导致的。解决方法是直接返回response,而不需要将其包装在HttpResponse中。如果仅用于下载目的,应该在定义response时使用StreamingHttpResponse()。

具体来说,可以按照以下步骤解决问题:

1. 在返回response时,直接使用return response,不需要使用HttpResponse进行包装。

2. 如果需要将文件作为可下载文件返回给前端,可以在定义response时使用StreamingHttpResponse,并设置Content-Disposition标头以指示浏览器将其识别为可下载文件。

以下是一个示例代码,展示了如何解决这个问题:

from django.http import StreamingHttpResponse
def download_file(request):
    # 生成文件内容
    file_content = "This is the content of the file."
    # 设置响应头
    response = StreamingHttpResponse(file_content, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename="eventlog.csv"'
    return response

通过上述代码,我们可以看到,在定义response时,使用StreamingHttpResponse,并设置Content-Disposition标头为'attachment; filename="eventlog.csv"',这样浏览器就会将返回的文件识别为可下载文件。

希望以上解决方法对你有帮助。如果有任何问题,请随时提问。

0
0 Comments

在Django中无法发送HttpResponse的问题出现的原因是因为无法将Django对象直接序列化为JSON格式。解决方法是使用Django的序列化器。

可以在Django的官方文档中找到有关序列化的详细信息,具体链接是:https://docs.djangoproject.com/en/dev/topics/serialization/

在相关问题中,某些情况下了类似的问题,他们遇到了" is not JSON serializable"的错误。可以在以下链接中找到相关的问题:<Django object > is not JSON serializable

0
0 Comments

无法从Django发送HttpResponse的原因是,simplejson和json不能很好地处理Django对象。Django内置的序列化器只能序列化填充有Django对象的查询集:

import json
from django.core import serializers
from django.http import HttpResponse
# 使用Django的序列化器将查询集序列化为json
data = serializers.serialize('json', self.get_queryset())
# 返回HttpResponse对象
return HttpResponse(data, content_type="application/json")

希望这能帮到你。

0