【问题标题】:Flask does not display JPG imageFlask 不显示 JPG 图像
【发布时间】:2021-10-26 09:30:55
【问题描述】:

我创建了一个简单的烧瓶应用程序来显示正在远程服务器上执行的一些图像分析的结果。

另一个应用把图片分析结果放在output.jpg,我想通过访问和地址http://localhost:5005/image_analysis_result来显示

只需参考函数get_image_analysis_result()

这是简单的 Flask 应用:

from flask import Flask, json, request 
import requests  
import socket
from datetime import date, datetime
from requests.models import Response
import os

JADE_REMOTE_IP = "10.1.0.8"
JADE_REMOTE_PORT = "7778"
IMAGE_RESULT_PATH = "/root/nana/nana/jade/jade/nana_edge_ai/nana_edge_ai/static/outputs/output.jpg"

def returnPublicIP():
    h_name = socket.gethostname()
    IP_address = socket.gethostbyname(h_name)
    return IP_address


#TODO: the URLs in services JSON need to be auto  generated to append UE capabilities
services =[{"id": 1,"type": "image_analysis","url": "http://"+returnPublicIP()+":5000/image_analysis"}]

#TODO: the URLs in services JSON need to be auto  generated to append gNodeB capabilities
image_result = [{"result_url":"http://"+JADE_REMOTE_IP+":"+JADE_REMOTE_PORT+"/acc"}]


class MockResponse(Response):
    def __init__(self,url='http://example.com', headers={'Content-Type':'text/html; charset=UTF-8'},status_code=200,reason = 'Success', _content = 'Some html goes here',json_ = None,encoding='UTF-8'):
        self.url = url
        self.headers = headers
        if json_ and headers['Content-Type'] == 'application/json':
            self._content = json.dumps(json_).encode(encoding)
        else:
            self._content = _content.encode(encoding)

        self.status_code = status_code
        self.reason = reason
        self.encoding = encoding

api = Flask(__name__)

def get_raw_request(request):
    request = request.prepare() if isinstance(request, requests.Request) else request
    headers = '\r\n'.join(f'{k}: {v}' for k, v in request.headers.items())
    body = '' if request.body is None else request.body.decode() if isinstance(request.body, bytes) else request.body
    return f'{request.method} {request.path_url} HTTP/1.1\r\n{headers}\r\n\r\n{body}'

@api.route('/services', methods=['GET'])
def get_services():
    return json.dumps(services)

#References: requests API : https://realpython.com/python-requests/
#References: #https://www.w3schools.com/python/ref_requests_response.asp
@api.route('/image_analysis', methods=['POST'])
def get_image_analysis():
    headers = {'User-Agent': 'Test'}
    #NEED TO SETUP WSIG JADE ADD-ON response = requests.get("http://"+JADE_REMOTE_IP+":"+JADE_REMOTE_PORT+"/acc")
    print(response.text)
    return response

#JUST LOOK AT THIS FUNCTION
@api.route('/image_analysis_result', methods=['GET'])
def get_image_analysis_result():
    headers = {'User-Agent': 'Test'}
    #1) result path 
    path = IMAGE_RESULT_PATH
    # Check whether the specified path exists or not
    isExist = os.path.exists(path)
    if (isExist==True):
        content = "<!DOCTYPE html><html><body><h1>sent message</h1><p><image width='100%' height='100%' src='{{url_for('static',filename = 'outputs/output.jpg')}}' ></p></body></html>"
    else:
        content = "<!DOCTYPE html><html><body><h1>sent message</h1><p>NO RESULT</p></body></html>"

    mock_response = MockResponse(
    headers={'Content-Type' :'application/html'},
    status_code=200,
    json_=json,
    reason='Success',
    _content=content)

    return mock_response.content


if __name__ == '__main__':
    api.run(host='0.0.0.0',port=5005, debug=True)

结果是一个损坏的img标签?

并且 Flask 服务器日志显示:

 * Detected change in '/root/nana/nana/jade/jade/nana_edge_ai/nana_edge_ai/nanaTestFlaskApi.py', reloading
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 195-909-187
127.0.0.1 - - [25/Oct/2021 17:32:03] "GET /image_analysis_result HTTP/1.1" 200 -
127.0.0.1 - - [25/Oct/2021 17:32:04] "GET /%7B%7Burl_for( HTTP/1.1" 404 -

如何修复图像输出?

赞赏。

【问题讨论】:

    标签: python flask


    【解决方案1】:

    这就是您的问题:您没有为/%7B%7Burl_for( 定义路径,是吗?

    127.0.0.1 - - [25/Oct/2021 17:32:04] "GET /%7B%7Burl_for( HTTP/1.1" 404 -
    

    我不知道MockResponse 应该对模板{{url_for('static',filename = 'outputs/output.jpg')}}' 做什么,但显然没有被扩展。

    【讨论】:

    • 他不应该“定义”一条名为/%7B%7Burl_for( 的路径。 /%7B%7Burl_for( 只是模板的烧瓶语法。
    • @Fredericka,我知道。但是模板语法(在路径中!)没有被解释,它保持不变并以这种方式显示在服务器日志中。
    【解决方案2】:

    首先,所有图像、css 和 JavaScript 文件都应位于与您的 nanaTestFlaskApi.py 位于同一文件夹中的“静态文件夹”中。此外,您使用的语法“{{}}”应该写在 html 文件中,并由 flask.rendertemplate() 处理。为了简单起见,我不会在此示例中使用它。 因此,考虑到这一点,新路径应该类似于 path = "static/image.jpg" 然后使用格式化字符串将路径放在内容中

    content = f"<!DOCTYPE html><html><body><h1>sent message</h1><p><image width='100%' height='100%' src='{path}' ></p></body></html>"
    

    现在您只需将其实现到您的类 MockResponse 中:

    resp = make_response(content)
    return resp
    

    另外,我不确定您为什么要使用自定义类。 flask 提供的两个类(makeresponse 和 render_template)几乎适用于所有东西。

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 2010-11-24
      • 2010-11-17
      • 2019-05-27
      • 2012-06-14
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多