python serve image and data using python BaseHttpRequestHandler











up vote
0
down vote

favorite












Hi I've the following code.



class Handler(BaseHTTPRequestHandler):
PAGE = """
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<link href='/favicon.ico' rel='shortcut icon'>
<style>
img {
width: 80%;
height: auto;
}
.left{
float:left;
}
.right{
float:left;
}
</style>
</head>
<body>
<div class="left">
<img src='/mjpeg'>
</div>
<div class="left">
<!-- SHOW DATA HERE -->
</div>

"""

PAGE_AFTER = """
</body>
</html>
"""

visualization_queue = None
predictionObj = None

def __init__(self, visualization_queue, *args, **kwargs):
self.visualization_queue = visualization_queue
super().__init__(*args, **kwargs)


def do_GET(self):

print('path hai ye')
print(self.path)
if self.path == '/mjpeg':
self.send_response(200)
self.send_header(
'Content-type',
'multipart/x-mixed-replace; boundary=--jpgboundary'
)
self.end_headers()

while True:
frame = self.get_info_from_queue() """<-- irrelevant"""

if frame is None:
print('no image from stream')
time.sleep(1)
continue

try:
ret, jpg = cv2.imencode('.jpg', frame)
self.wfile.write(bytes("--jpgboundaryn", "utf8"))
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-length', len(jpg))
self.end_headers()
self.wfile.write(jpg)

# time.sleep(self.config.delay)
except (BrokenPipeError, ConnectionResetError):
print('connection closed')
break
elif self.path == "/favicon.ico":
print('getting favicon')
icon = io.open("Common/logo-alten.png", "rb").read()
self.send_response(200)
self.send_header('Content-type', 'mage/x-icon')
self.send_header('Content-length', len(icon))
self.end_headers()
self.wfile.write(icon)
elif self.path == "/":
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes(self.PAGE + self.PAGE_AFTER, "utf8"))
else:
print('error', self.path)
self.send_response(404)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes('<html><head></head><body>', "utf8"))
self.wfile.write(bytes('<h1>{0!s} not found</h1>'.format(self.path), "utf8"))
self.wfile.write(bytes('</body></html>', "utf8"))

return


class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""


I am trying to show a video on the localhost:8080 of my server. The problem is that I am able to succesfully send video frames as you can see in the following part of the code .



ret, jpg = cv2.imencode('.jpg', frame)
self.wfile.write(bytes("--jpgboundaryn", "utf8"))
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-length', len(jpg))
self.end_headers()
self.wfile.write(jpg)


What I want now is also to send additional data in the form of html, for e.g



<ol>
<li>Person: 0</li>
<li>cars: 5</li>
</ol>


To show along on the side of the page. Can anybody point me in the right direction ? Any solutions ?



Thanks.










share|improve this question






















  • You generally don't... you could put the jpeg encoded as the "src" of the image element and then the rest of the content as additional data, then count the length of that combined, or, you put the image returned as a separate function with a link to the image and just return the html that indicates to the browser it should then retrieve the image from another link... that or just use a micro-framework such as flask and save yourself a huge amount of frustration...
    – Jon Clements
    Nov 22 at 16:27












  • hi Jon thanks for the answer. Is it possible for you to give a very simple small code example. I'll highly appreciate it.
    – Mj1992
    Nov 23 at 9:09










  • Start with stackabuse.com/serving-static-files-with-flask - that'll cover everything you're trying to achieve... (but in a much, much, simpler way :p)
    – Jon Clements
    Nov 23 at 9:26










  • thanks man that'll work
    – Mj1992
    Nov 23 at 11:35















up vote
0
down vote

favorite












Hi I've the following code.



class Handler(BaseHTTPRequestHandler):
PAGE = """
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<link href='/favicon.ico' rel='shortcut icon'>
<style>
img {
width: 80%;
height: auto;
}
.left{
float:left;
}
.right{
float:left;
}
</style>
</head>
<body>
<div class="left">
<img src='/mjpeg'>
</div>
<div class="left">
<!-- SHOW DATA HERE -->
</div>

"""

PAGE_AFTER = """
</body>
</html>
"""

visualization_queue = None
predictionObj = None

def __init__(self, visualization_queue, *args, **kwargs):
self.visualization_queue = visualization_queue
super().__init__(*args, **kwargs)


def do_GET(self):

print('path hai ye')
print(self.path)
if self.path == '/mjpeg':
self.send_response(200)
self.send_header(
'Content-type',
'multipart/x-mixed-replace; boundary=--jpgboundary'
)
self.end_headers()

while True:
frame = self.get_info_from_queue() """<-- irrelevant"""

if frame is None:
print('no image from stream')
time.sleep(1)
continue

try:
ret, jpg = cv2.imencode('.jpg', frame)
self.wfile.write(bytes("--jpgboundaryn", "utf8"))
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-length', len(jpg))
self.end_headers()
self.wfile.write(jpg)

# time.sleep(self.config.delay)
except (BrokenPipeError, ConnectionResetError):
print('connection closed')
break
elif self.path == "/favicon.ico":
print('getting favicon')
icon = io.open("Common/logo-alten.png", "rb").read()
self.send_response(200)
self.send_header('Content-type', 'mage/x-icon')
self.send_header('Content-length', len(icon))
self.end_headers()
self.wfile.write(icon)
elif self.path == "/":
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes(self.PAGE + self.PAGE_AFTER, "utf8"))
else:
print('error', self.path)
self.send_response(404)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes('<html><head></head><body>', "utf8"))
self.wfile.write(bytes('<h1>{0!s} not found</h1>'.format(self.path), "utf8"))
self.wfile.write(bytes('</body></html>', "utf8"))

return


class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""


I am trying to show a video on the localhost:8080 of my server. The problem is that I am able to succesfully send video frames as you can see in the following part of the code .



ret, jpg = cv2.imencode('.jpg', frame)
self.wfile.write(bytes("--jpgboundaryn", "utf8"))
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-length', len(jpg))
self.end_headers()
self.wfile.write(jpg)


What I want now is also to send additional data in the form of html, for e.g



<ol>
<li>Person: 0</li>
<li>cars: 5</li>
</ol>


To show along on the side of the page. Can anybody point me in the right direction ? Any solutions ?



Thanks.










share|improve this question






















  • You generally don't... you could put the jpeg encoded as the "src" of the image element and then the rest of the content as additional data, then count the length of that combined, or, you put the image returned as a separate function with a link to the image and just return the html that indicates to the browser it should then retrieve the image from another link... that or just use a micro-framework such as flask and save yourself a huge amount of frustration...
    – Jon Clements
    Nov 22 at 16:27












  • hi Jon thanks for the answer. Is it possible for you to give a very simple small code example. I'll highly appreciate it.
    – Mj1992
    Nov 23 at 9:09










  • Start with stackabuse.com/serving-static-files-with-flask - that'll cover everything you're trying to achieve... (but in a much, much, simpler way :p)
    – Jon Clements
    Nov 23 at 9:26










  • thanks man that'll work
    – Mj1992
    Nov 23 at 11:35













up vote
0
down vote

favorite









up vote
0
down vote

favorite











Hi I've the following code.



class Handler(BaseHTTPRequestHandler):
PAGE = """
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<link href='/favicon.ico' rel='shortcut icon'>
<style>
img {
width: 80%;
height: auto;
}
.left{
float:left;
}
.right{
float:left;
}
</style>
</head>
<body>
<div class="left">
<img src='/mjpeg'>
</div>
<div class="left">
<!-- SHOW DATA HERE -->
</div>

"""

PAGE_AFTER = """
</body>
</html>
"""

visualization_queue = None
predictionObj = None

def __init__(self, visualization_queue, *args, **kwargs):
self.visualization_queue = visualization_queue
super().__init__(*args, **kwargs)


def do_GET(self):

print('path hai ye')
print(self.path)
if self.path == '/mjpeg':
self.send_response(200)
self.send_header(
'Content-type',
'multipart/x-mixed-replace; boundary=--jpgboundary'
)
self.end_headers()

while True:
frame = self.get_info_from_queue() """<-- irrelevant"""

if frame is None:
print('no image from stream')
time.sleep(1)
continue

try:
ret, jpg = cv2.imencode('.jpg', frame)
self.wfile.write(bytes("--jpgboundaryn", "utf8"))
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-length', len(jpg))
self.end_headers()
self.wfile.write(jpg)

# time.sleep(self.config.delay)
except (BrokenPipeError, ConnectionResetError):
print('connection closed')
break
elif self.path == "/favicon.ico":
print('getting favicon')
icon = io.open("Common/logo-alten.png", "rb").read()
self.send_response(200)
self.send_header('Content-type', 'mage/x-icon')
self.send_header('Content-length', len(icon))
self.end_headers()
self.wfile.write(icon)
elif self.path == "/":
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes(self.PAGE + self.PAGE_AFTER, "utf8"))
else:
print('error', self.path)
self.send_response(404)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes('<html><head></head><body>', "utf8"))
self.wfile.write(bytes('<h1>{0!s} not found</h1>'.format(self.path), "utf8"))
self.wfile.write(bytes('</body></html>', "utf8"))

return


class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""


I am trying to show a video on the localhost:8080 of my server. The problem is that I am able to succesfully send video frames as you can see in the following part of the code .



ret, jpg = cv2.imencode('.jpg', frame)
self.wfile.write(bytes("--jpgboundaryn", "utf8"))
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-length', len(jpg))
self.end_headers()
self.wfile.write(jpg)


What I want now is also to send additional data in the form of html, for e.g



<ol>
<li>Person: 0</li>
<li>cars: 5</li>
</ol>


To show along on the side of the page. Can anybody point me in the right direction ? Any solutions ?



Thanks.










share|improve this question













Hi I've the following code.



class Handler(BaseHTTPRequestHandler):
PAGE = """
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<link href='/favicon.ico' rel='shortcut icon'>
<style>
img {
width: 80%;
height: auto;
}
.left{
float:left;
}
.right{
float:left;
}
</style>
</head>
<body>
<div class="left">
<img src='/mjpeg'>
</div>
<div class="left">
<!-- SHOW DATA HERE -->
</div>

"""

PAGE_AFTER = """
</body>
</html>
"""

visualization_queue = None
predictionObj = None

def __init__(self, visualization_queue, *args, **kwargs):
self.visualization_queue = visualization_queue
super().__init__(*args, **kwargs)


def do_GET(self):

print('path hai ye')
print(self.path)
if self.path == '/mjpeg':
self.send_response(200)
self.send_header(
'Content-type',
'multipart/x-mixed-replace; boundary=--jpgboundary'
)
self.end_headers()

while True:
frame = self.get_info_from_queue() """<-- irrelevant"""

if frame is None:
print('no image from stream')
time.sleep(1)
continue

try:
ret, jpg = cv2.imencode('.jpg', frame)
self.wfile.write(bytes("--jpgboundaryn", "utf8"))
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-length', len(jpg))
self.end_headers()
self.wfile.write(jpg)

# time.sleep(self.config.delay)
except (BrokenPipeError, ConnectionResetError):
print('connection closed')
break
elif self.path == "/favicon.ico":
print('getting favicon')
icon = io.open("Common/logo-alten.png", "rb").read()
self.send_response(200)
self.send_header('Content-type', 'mage/x-icon')
self.send_header('Content-length', len(icon))
self.end_headers()
self.wfile.write(icon)
elif self.path == "/":
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes(self.PAGE + self.PAGE_AFTER, "utf8"))
else:
print('error', self.path)
self.send_response(404)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes('<html><head></head><body>', "utf8"))
self.wfile.write(bytes('<h1>{0!s} not found</h1>'.format(self.path), "utf8"))
self.wfile.write(bytes('</body></html>', "utf8"))

return


class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""


I am trying to show a video on the localhost:8080 of my server. The problem is that I am able to succesfully send video frames as you can see in the following part of the code .



ret, jpg = cv2.imencode('.jpg', frame)
self.wfile.write(bytes("--jpgboundaryn", "utf8"))
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-length', len(jpg))
self.end_headers()
self.wfile.write(jpg)


What I want now is also to send additional data in the form of html, for e.g



<ol>
<li>Person: 0</li>
<li>cars: 5</li>
</ol>


To show along on the side of the page. Can anybody point me in the right direction ? Any solutions ?



Thanks.







python http multipartform-data basehttprequesthandler






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 at 16:20









Mj1992

1,473104480




1,473104480












  • You generally don't... you could put the jpeg encoded as the "src" of the image element and then the rest of the content as additional data, then count the length of that combined, or, you put the image returned as a separate function with a link to the image and just return the html that indicates to the browser it should then retrieve the image from another link... that or just use a micro-framework such as flask and save yourself a huge amount of frustration...
    – Jon Clements
    Nov 22 at 16:27












  • hi Jon thanks for the answer. Is it possible for you to give a very simple small code example. I'll highly appreciate it.
    – Mj1992
    Nov 23 at 9:09










  • Start with stackabuse.com/serving-static-files-with-flask - that'll cover everything you're trying to achieve... (but in a much, much, simpler way :p)
    – Jon Clements
    Nov 23 at 9:26










  • thanks man that'll work
    – Mj1992
    Nov 23 at 11:35


















  • You generally don't... you could put the jpeg encoded as the "src" of the image element and then the rest of the content as additional data, then count the length of that combined, or, you put the image returned as a separate function with a link to the image and just return the html that indicates to the browser it should then retrieve the image from another link... that or just use a micro-framework such as flask and save yourself a huge amount of frustration...
    – Jon Clements
    Nov 22 at 16:27












  • hi Jon thanks for the answer. Is it possible for you to give a very simple small code example. I'll highly appreciate it.
    – Mj1992
    Nov 23 at 9:09










  • Start with stackabuse.com/serving-static-files-with-flask - that'll cover everything you're trying to achieve... (but in a much, much, simpler way :p)
    – Jon Clements
    Nov 23 at 9:26










  • thanks man that'll work
    – Mj1992
    Nov 23 at 11:35
















You generally don't... you could put the jpeg encoded as the "src" of the image element and then the rest of the content as additional data, then count the length of that combined, or, you put the image returned as a separate function with a link to the image and just return the html that indicates to the browser it should then retrieve the image from another link... that or just use a micro-framework such as flask and save yourself a huge amount of frustration...
– Jon Clements
Nov 22 at 16:27






You generally don't... you could put the jpeg encoded as the "src" of the image element and then the rest of the content as additional data, then count the length of that combined, or, you put the image returned as a separate function with a link to the image and just return the html that indicates to the browser it should then retrieve the image from another link... that or just use a micro-framework such as flask and save yourself a huge amount of frustration...
– Jon Clements
Nov 22 at 16:27














hi Jon thanks for the answer. Is it possible for you to give a very simple small code example. I'll highly appreciate it.
– Mj1992
Nov 23 at 9:09




hi Jon thanks for the answer. Is it possible for you to give a very simple small code example. I'll highly appreciate it.
– Mj1992
Nov 23 at 9:09












Start with stackabuse.com/serving-static-files-with-flask - that'll cover everything you're trying to achieve... (but in a much, much, simpler way :p)
– Jon Clements
Nov 23 at 9:26




Start with stackabuse.com/serving-static-files-with-flask - that'll cover everything you're trying to achieve... (but in a much, much, simpler way :p)
– Jon Clements
Nov 23 at 9:26












thanks man that'll work
– Mj1992
Nov 23 at 11:35




thanks man that'll work
– Mj1992
Nov 23 at 11:35

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53434926%2fpython-serve-image-and-data-using-python-basehttprequesthandler%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53434926%2fpython-serve-image-and-data-using-python-basehttprequesthandler%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

What visual should I use to simply compare current year value vs last year in Power BI desktop

Alexandru Averescu

Trompette piccolo