如何使用HttpResponse在Django中显示图像

2024-09-27 21:26:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用下面的行显示python脚本输出的图像,但不是在浏览器中显示,而是下载文件而不是显示代码

这是我在views.py中创建的函数:

def adc(请求): file=“C:\Users\TheBoss\Downloads\New\u test.xlsx” df=pd.read\u excel(文件、工作表\u name='Graph')

plt.plot(df['Date'], df['Video Device - Not Responding'], label = 'Video Device - Not Responding')
#plt.plot(df['Date'], df['30th Apr'], 'b', label = '30-Apr')
plt.xticks(rotation=45)

plt.tick_params(axis='x', which='major', labelsize=6)
# naming the y axis
plt.ylabel('Condition Count')

# giving a title to my graph
plt.title('Condition')

# function to show the plot
plt.legend()
#plt.show()
plt.savefig('C:\\Users\\TheBoss\\Downloads\\test.png')


image_data = open("C:\\Users\\TheBoss\\Downloads\\test.png", "rb").read()
return HttpResponse(image_data, content_type="test/png")

Tags: 文件testdfreaddateplotpngdevice
1条回答
网友
1楼 · 发布于 2024-09-27 21:26:28

通常,这应该足以以内联方式显示图像

def adc(request): 
    file = "C:\Users\TheBoss\Downloads\New_test.xlsx"
    df = pd.read_excel(file, sheet_name='Graph')

    plt.plot(df['Date'], df['Video Device - Not Responding'], label = 'Video Device - Not Responding')
    plt.xticks(rotation=45)
    plt.tick_params(axis='x', which='major', labelsize=6)
    plt.ylabel('Condition Count')
    plt.title('Condition')
    plt.legend()
    
    buffer = io.BytesIO()
    plt.savefig(buffer, format='png')
    return HttpResponse(buffer.getvalue(), content_type="test/png")

它应该在大多数浏览器中显示为图像,如果您想在HTML中插入图像,您可以使用一个简单的

<img src="{% url 'my_image' %}">

我从经验中知道,这在Edge、Firefox和Opera中都有效。有时浏览器需要额外的说服力来内联显示图像,在这种情况下,将头Content-Disposition设置为inline通常是有效的

相关问题 更多 >

    热门问题