Issue
Using requests I am fetching an image from a server. Instead of writing this file out and then using it to load into the template, I am trying to parse the contents onto the view (image data inline or another method).
Below is the partial output from r.contents:
b'/x89PNG/r/n/x1v/n/x0e/x20/x20/rIHDR/x00/x00/x22/xdb/x00/x00/x01/xad/x08/x06/x00/x00/x00/xc7/xe3/xb8/xe9/x10/x00/x00/x06bKGD/x00/xff/x00/xcf/x00/
Since its bytes, I tried to encode using base64 and then pass into the image data-url but haven't been able to render. Below is the partial output:
<img id="now" style="max-width: 100%; width: auto;" alt="" src="data:image/png;base64,b'iVBSDFSGcANSUhEUgAAAtsAAAGtCAYAAADH47jpAAAABmJLR0QA/wD/AP+gvSDFsfgsbfbvdsdsbdgndfnOy9eZwcV3nv/autt+mWRqPVY2ksCckWljXacAggexQvQK4NiXHEa1+JsbdfghgcEEOwlBwvHNIL8xvpFmwpIABl8I2HEYzJ4bY48AAzbyaEG2Lxfg463dR/Xpqaqufeuq6uf7+fSnu6vq1HOe012nTv3qqecABEEQBEfgdrcgbQBEEQBEEQBEEQBEEQBEEQfgdfgEEQBEEQAMA1
Is there a way to get this to work?
Below is the sample view code in use, the code is meant to give an idea of this question:
def graph(request):
unix_time = int(time())
r = requests.get(f'http://192.168.1.10/graph.php?type=multi-port_bits_duo_separate&idb=393,204,132,31,36,214&to={unix_time}', auth=(USERNAME,PASS), stream=True)
r.raise_for_status()
# the write to file method, works but trying to stream contents into view
#with open(f'{unix_time}.png','wb') as fd:
# for chunk in r.iter_content(chunk_size=50000):
# fd.write(chunk)
context = {'context': r.content}
return render(request, 'live_graph.html', context)
Solution
The output of base64.b64encode()
(which I'm assuming you're using) is bytes
. You need to convert that to a string before you hand it to the template for rendering.
For example:
decoded = base64.b64encode(r.content).decode('ascii') # Convert to a string first
context = {'imagedata': decoded}
return render(request, 'live_graph.html', context)
And then in the template:
<img id="now" style="max-width: 100%; width: auto;" alt="" src="data:image/png;base64,{{ imagedata }}"/>
The clue here was the initial b'
in your example base64 image data. That corresponds to b'
which of course you don't actually want in the base64 encoded string itself.
Answered By - Will Keeling
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.