How render binary image in javascript - javascript

My flask python app return an image as a response from a POST request:
def upload_file():
if request.method == 'POST':
return send_file('1.png', mimetype='image/png')
Then I want to use javascript and jquery ajax to do the request, and the response is:
success: function(img_response) {
console.log(img_response);
}
�PNG
���
IHDR����������?1��
�IDATx����nIv��vdU�Ѓ�ۀm6f`�����?���W3�1��%6Y��ER�xh�Pb��]�R�DfeFF�qo��_����O�4�]J$��.�%E�%E�ɲ$)...
How can I render this type of file in browser?
Maybe is better decode the image in base64 in flask, but how can I do it?

You should take a look here for encoding a binary to base64 with python. Once you got it, send the string to your app (frontend) as a response, then you can add something like:
<img id="myImgTag" src="data:image/png;base64, YOUR_BASE64_STRING_FROM_RESPONSE"></img>
You can add it with javascript with something like:
let img = document.getElementById('myImgTag').setAttribute('src','data:image/png;base64, YOUR_BASE64_STRING_FROM_RESPONSE')
====EDIT===
To read the file and encode it to base64 do the following:
import base64
...
myImage = open('your_file_name','rb')
myBase64File = base64.b64encode(myImage.read())
Then just use Flask to send 'myBase64File' var as you want (might be inside a JSON, as plain text, etc.)

Related

How to package plain JSON content in a WSGI response?

I have a Django WSGI (not my decision) website making a call to fetch dynamically generated JavaScript. I put the function in views.py and it's receiving the request and doing the work, but the return value is being rejected.
The HTML (JavaScript section of web page) that calls this function does it like this:
var jscript = document.createElement('script');
jscript.id = 'generate';
jscript.style.visibility = 'hidden';
jscript.style.display = 'none';
jscript.src = `/generate?callback=catchOptions${query}`; // jsonp https://en.wikipedia.org/wiki/JSONP query is a list of parameters in query string format
if (document.getElementById("generate") == null)
document.body.appendChild(jscript); // javascript needs this to work properly
There's map file that maps /generate to /generate_planet (see below). Getting into the function works great. It's the return value that Djangoff is rejecting.
Here is the function in views.py
from cgitb import reset
from django.shortcuts import render
from . import planetor
from django.http import JsonResponse
def generate_planet(request):
res = planetor.generate(request.content_params, "/app/planetor/", "FRAMES=1")
# res is JSON text, NOT a python dict
return res
# res looks like this:`callback({'camera_location': '-30,-30,-30', 'camera_angle': '30', 'sun_color': '5,5,5', 'sun_position': '10000,0,-10000', 'planet_size': '20.06', 'background': 'background_2.jpg', 'planet': 'surface_1.jpg', 'clouds_size': '1.02', 'clouds': 'clouds_16.jpg', 'clouds_density': '0.80', 'atmosphere': 'iodine', 'atmosphere_density': '0.95', 'atmosphere_size': '1.03', 'moons': '4', 'moon_position': None, 'moon_size': None, 'moon': None, 'random_color': None, 'random_float': None, 'random_trans': None, 'star_system': 'Barnard', 'star_index': 'Zeta', 'planet_index': 'II', 'planet_type': 'Surface ', 'identity': '81654447928', 'designation': 'v_star_index v_star_system v_planet_index', 'clouds_file': 'clouds_16.jpg'})
The function call actually works, and the "planetor.generate()" runs. The problem is, the return JSON (JSONP really) from this, is rejected by Djangoff
Djangoff spits out this:
Internal Server Error: /generate_planet
Traceback (most recent call last):
File "/usr/local/lib/python3.9/dist-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/usr/local/lib/python3.9/dist-packages/django/utils/deprecation.py", line 119, in __call__
response = self.process_response(request, response)
File "/usr/local/lib/python3.9/dist-packages/django/middleware/clickjacking.py", line 33, in process_response
response.headers['X-Frame-Options'] = self.get_xframe_options_value(
AttributeError: 'dict' object has no attribute 'headers'
[05/Jun/2022 16:52:11] "GET /generate_planet? HTTP/1.1" 500 56694
It's looking for the return value to be wrapped in something I'm sure but for the life of my I can't find 1) any API documents for WSGIResponse to I can construct one and 2) examples of anyone doing anything like this with Djangoff
I eventually figured this out.
If you send a request to Django, like this:
/my_request?key1=value1&key2=value2&key3=value3
By whatever means (raw URL, form submit, ajax request, whatever)
To have Django catch that request and return a JSON answer put a function like this in views.py
def my_request(request):
selections = request.GET # <== this gets the query string paramaters as a dictionary
# use the query string parameters as the parameters of the function for creating the answer to the request
res = {"answer1":"value1","answer2":"value2"} # << python dictionary of answer
return JsonResponse(res) # convert dictionary to JSON
If you want to get JSONP back, you'll have to just code the raw javascript:
return 'callback({"answer1":"value1","answer2":"value2"})'

How to send file with react and django rest

How can I send an image file from react to django.
I am new to react and django , currently I am being successful in sending and getting data from/to the endpoints, now I want to send an image file or any other file from react to django or get image file from django to react.I wrote some code but its not working properly and i am facing quite difficulty to send file, I researched but not get any useful link.Kindly can someone share link from where I can get better understanding how it works.Here below is my try:
REACT PART
let doc=new JsPDF();
doc.addImage(img,'JPEG',30,30);
//doc.save('test.pdf');
let formdata=new FormData();
formdata.append('file',doc);
fetch(`http://127.0.0.1:8000/chauffeur/pdf_upload/`,
{
method: 'POST',
body:formdata,
}
).then(response => response.json()).catch(error => console.error('Error:', error));
DJANGO PART
class PdfUpload(APIView):
parser_classes = (MultiPartParser, FormParser,)
def get(self, request):
return Response([PdfSerializer(file).data for file in Pdf.objects.all()])
def post(self,request):
payload=(request.data,request.FILES)
print("Hello")
print(payload)
serializer=PdfSerializer(data=payload)
if serializer.is_valid():
serializer.save()
return Response("File Saved in Backend",status=status.HTTP_201_CREATED)
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
But I am getting too many errors from above code, like no file submitted or expected dict but receive list, can someone fix above code or can share helpful links from where I can understand better.Thanks in advance!
If the name of object in your models.py is for example PdfModel write like this:
from django.core.files import File
def post(self, request):
my_file = File(request.data.get('file'))
new_pdf_file = PdfModel.objects.create(
field1=request.data.get('field1'),
field2=request.data.get('field2'),
field3=my_file )
new_pdf_file.save()
return Response({"something","something")

I have a file that is encoded in RIFF. How can I send this file through an ajax post response?

I am trying to preserve the RIFF encoding of the file while sending it back as a response, as shown below.
router.post('/someroute', function(req,res,next){
var riff1= fs.readFileSync(somefilepath);
res.send(riff1);
}
When I receive a response from my AJAX call, and examine the response it is in an ASCII format. I have tried to change the encoding of readFileSync to utf8, but that isn't working. How can I achieve this?
Use a Blob();
var riff1 = fs.readFileSync(somefilepath);
var blob = new Blob([riff1], {type: 'audio/mpeg'});
res.send(blob);
Should work.

How to stream data from python to javascript

I am looking for a way to stream data from python script to a javascript within a html file.
My data is stored in a large csv file which looks like:
x1,x2,y1,y2
0.5,0.54,0.04,0.55
0.12,0.88,1.02,0.005
...
...
The python script must pre-process this data before sending it to javascript:
import csv
def send_data(filename):
with open(filename, "rb") as csvfile:
datareader = csv.reader(csvfile)
for row in datareader:
preprocessed = Do_something(row)
yield preprocessed
The javascript should process the received data from the python script above.
Without knowing more about your exact requirements you could do something like this using circuits:
Code: (untested)
import csv
from circuits.web import Server, Controller
def Do_something(row):
return row
class Root(Controller):
def send_data(self, filename):
self.response.stream = True
with open(filename, "rb") as csvfile:
datareader = csv.reader(csvfile)
for row in datareader:
preprocessed = Do_something(row)
yield preprocessed
app = Server(("0.0.0.0", 8000))
Root().register(app)
app.run()
Then requests to http://localhost:8000/send_data/filename would result in a stream resolve of the entire csv file. This also assumes you actually want to serve up the csv file as a web response to some web application.

Problems loading JSON code in Python

I've been tyring to figure out how to load JSON objects in Python.
I'm able to send a JSON string to the server, but there it fails.
This is what I'm sending through a websocket with JavaScript:
ws.send('{"test":"test"}');
The server receives it without a problem, but can't validate it:
{"test":"test"}
This is not a JSON object!
Which comes forth from this code:
try:
data = data[:-1]
json.loads(data)
except ValueError:
print 'This is not a JSON object!'
else:
print ('JSON found!')
The data = data[:-1] is there to strip the delimiter sent through the websocket.
import traceback
try:
d = json.loads(data[data.index('{'):-1])
except:
traceback.print_exc()
else:
print(d)
This way only the dictionary part of the data-string is parsed to json.loads().

Categories

Resources