Django rest框架返回图像作为响应

2024-09-26 17:55:29 发布

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

我调用django rest框架getapi来创建条形码。当我试图将它保存为图像时,它工作得很好。在

@api_view(['GET'])
def mybarcode(request):
    from elaphe import barcode

        code = barcode('datamatrix', "sampletext",
                       encoding='utf-8', scale=2,
                       options=dict(columns=24, rows=24),
                       margin=2, data_mode='50bits')
        code.save("mybarcode.jpg")
        return Response({'status': True})

当我将这个API称为“http://127.0.0.1:9999/api/v1/testbarcode”时,这一切都很好。将创建一个名为“我的条形码.jpg“并且api将其状态返回为True。在

但是我想返回这个api调用的结果图像。因为我必须在一个图像标签中包含这个。在

^{pr2}$

有办法吗?在


Tags: django图像框架viewrestapitrueget
2条回答

应避免在Django视图中返回图像/文件。Web服务器NGINX/Apache很擅长处理它们。在

将映像保存在一个存储中,比如本地磁盘、aws3或其他云存储。然后根据图像的存储位置渲染图像。在

在本地存储的情况下,可以使用web服务器交付。存储在aws3中的图像可以通过AWS CDN Cloudfront提供。在

用于将图像转换为base64

import base64
def(yourimagefile):
     with open(yourimagefile, "rb") as image_file:
         base64string = base64.b64encode(image_file.read())
         return base64string

在创建图像后钩住这个模块,并更改html以显示base64内容

相关问题 更多 >

    热门问题