【问题标题】:Django Read png image from url then pass it to HttpResponseDjango 从 url 读取 png 图像,然后将其传递给 HttpResponse
【发布时间】:2018-01-30 02:15:37
【问题描述】:

我想从私有 url 读取 png 图像,然后将其写入 HttpResponse。 我有这个视图,它将从 geoServer 获取一个图层作为 png 图像,然后打开它并读取它,然后将其作为 HttpResponse 返回:

def get_layer(request):
   #this url will return png image
   url='https://example.com/geoserver/layer/wms?.......' 
   r = requests.get(url)
   with open(r, "rb") as fp:
       img = Image.open(fp)
   return HttpResponse(img)

我收到一个错误:

Exception Type: TypeError
Exception Value: invalid file: Response [200]

/main/views.py in test1
    with open(r, "rb") as fp: ...
▼ Local vars
Variable    Value
r           <Response [200]>
request     <WSGIRequest: GET '/test/'>
url         'https://example.com/geoserver/layer/wms?.......'

我想要的只是从 url 获取 png 文件,然后将其传递给 HttpResponse,因此当有人调用我的视图时,他/她将仅使用我的 Django 路径获取图像。我不想在本地保存图像我只想将它分配给一个变量并传递它。 我正在使用:Django 1.11,python3.5。

【问题讨论】:

    标签: django python-3.x python-imaging-library


    【解决方案1】:

    这行得通吗?

    def get_layer(request):
       #this url will return png image
       url='https://example.com/geoserver/layer/wms?.......' 
       r = requests.get(url)
       return HttpResponse(r.content, content_type="image/png")
    

    【讨论】:

    • @Anatol 相信这应该适用于任何类型的图像是的,当 content_type 正确提供时
    猜你喜欢
    • 1970-01-01
    • 2011-04-19
    • 2013-10-25
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多