I created a simple flask app to show results of some image analysis that is being performed on a remote server.
Another app places the image analysis result as output.jpg
, that I would like to display by accessing and address http://localhost:5005/image_analysis_result
Just refer to the function get_image_analysis_result()
:
Here is the simple Flask app:
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)
The result is a broken img tag?
And Flask server log shows:
* 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 /{{url_for( HTTP/1.1" 404 -
How can I fix the image output?
Appreciated.
CodePudding user response:
Here's your problem right here: You did not define a path for /{{url_for(
, did you?
127.0.0.1 - - [25/Oct/2021 17:32:04] "GET /{{url_for( HTTP/1.1" 404 -
I don't know what MockResponse
is supposed to do with the template {{url_for('static',filename = 'outputs/output.jpg')}}'
, but clearly is not being expanded.
CodePudding user response:
First, all images, css and JavaScript files should be in a "static folder" that is in the same folder as your nanaTestFlaskApi.py. Also, the syntax "{{}}" that you are using is suposed to be written in a html file and is processend by flask.rendertemplate(). I won't use it in this example to keep things simple.
So with that in mind, the new path sould be something like path = "static/image.jpg"
Then you place your path in the content using a formated string
content = f"<!DOCTYPE html><html><body><h1>sent message</h1><p><image width='100%' height='100%' src='{path}' ></p></body></html>"
Now you just have to implement this into your class MockResponse:
resp = make_response(content)
return resp
Also, i am not sure why you are using a custom class. The two class (makeresponse & render_template) provided by flask are well fitted for almost everything.