JSON Response output is not updated on single click event - javascript

I am trying to build a java online compiler web app using django.
but every time I submit my code through AJAX call the new code is posted successfully to view.py but the JSON response object is still the previous one.
def code1(request):
response_data={}
**codet=request.POST.get("code","")** # getting the code text from Ajax req
**output=code(codet)** #sending code for execution
response_data['result']="Successful" #storing in response
response_data['message']=output
**return HttpResponse(json.dumps(response_data), content_type="application/json")**
def code(code_text):
return execute(code_text)
def execute(code_text):
filename_code=open('Main.java','w+') #creating file
filename_code.flush()
f1 = code_text.split("\n") # splitting code line by line
for i in f1:
filename_code.write(i+"\n") #writing code line by line
filename_code.close() #closing file
time.sleep(2) #giving wait
**compile_java(filename_code)**
#compiling file (Note: I am not using the file passed in compile_java)
**return execute_java(filename_code,input**) #running java file
def compile_java(java_file):
proc = subprocess.Popen('javac Main.java', shell=True)
def execute_java(java_file, stdin):
#java_class,ext = os.path.splitext(java_file)
cmd = ['java ', 'Main']
proc = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
stdout,stderr = proc.communicate(stdin)
stdoutstr= str(stdout,'utf-8')
**
1. return stdoutstr
**
Actually the previous json response is being sent for current code(codet)

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"})'

Render template in Django view after AJAX post request

I have managed to send & receive my JSON object in my views.py with a POST request (AJAX), but am unable to return render(request, "pizza/confirmation.html"). I don't want to stay on the same page but rather have my server, do some backend logic on the database and then render a different template confirming that, but I don't see any other way other than AJAX to send across a (large) JSON object. Here is my view:
#login_required
def basket(request):
if request.method == "POST":
selection = json.dumps(request.POST)
print(f"Selection is", selection) # selection comes out OK
context = {"test": "TO DO"}
return render(request, "pizza/confirmation.html", context) # not working
I have tried checking for request.is_ajax() and also tried render_to_string of my html page, but it all looks like my mistake is elsewhere. Also I see in my terminal, that after my POST request, a GET request to my /basket url is called - don't understand why.
Here is my JavaScript snippet:
var jsonStr = JSON.stringify(obj); //obj contains my data
const r = new XMLHttpRequest();
r.open('POST', '/basket');
const data = new FormData();
data.append('selection', jsonStr);
r.onload = () => {
// don't really want any callback and it seems I can only use GET here anyway
};
r.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
r.send(data);
return false;
In your basket view function, you always render the template as response. You can pass the parameters to your js snippet via HttpResponse. After request completed and you have response in your js function, you can use window.location.href to redirect the page you want. You can also look this answer to get more information.

Passing a variable received by flask through HTTP post to JavaScript in html template on flask?

So I'm creating a python app that counts detected objects using OpenCV then passing the counter variable to Flask server using the following HTTP post request:
requests.post('http://127.0.0.1:5000', json = {'count': count})
, the flask sever receives the variable then pass it to a JavaScript within the html template, here is the code of flask server:
app = Flask(__name__)
#app.route("/",methods=['GET', 'POST'])
def index():
content = request.get_json(silent=True)
if content :
cnt = content.get('count') #get JSON from OpenCV every time the count is updated
print cnt # here it prints the variable to the cmd and show me the count update
return render_template("test.html", cnt = cnt); #here the value is passed as zero ?!
if __name__ == "__main__":
app.run(debug=True)
and when I run the 'test.html' template it only show me the 'cnt' variable = 0, although I'm getting the updated value constantly from my OpenCV code to my flask server.
here is the script part of my 'test.html'
<p>People count: <span id="counti"></span></p>
<script>
var countn = '{{cnt}}';
document.getElementById('counti').innerHTML = countn
</script>
I want my 'count' variable to pass smoothly from OpenCV and receive into my Javascript to be able to make my web-app able to make decisions based on the count of objects observed by OpenCV.
What is the optimal way to do this ?
I really appreciate your help!

Python Flask, custom status of background process as response

I'm having trouble returning a custom response from a background process that takes a long time and its being called from a view function in Flask. I use the EventSource method from the html to display the status of the process to the user. The process is encapsulated in an object instanced in the view function and I need a way to signalize the status of the process.
The significant parts of the object are:
class MyObject:
self.status = 0
def signal_status(self):
yield self.status
def doSomeProcess(self):
self.status = 1
self.foo()
self.status = 2
self.bar()
self.status = 3
def process_call(self):
Thread(target=self.async_process, args=(app, data)).start()
def async_process(self, app, data):
with app.app_context():
self.doSomeProcess(data)
And from the routes:
myObj = MyObject()
#app.route('/process/<data>')
def process(data):
global myObject
myObject.process_call(data)
return render_template('process.html')
#app.route('/progress')
def progress():
global myObject
return Response(myObject.signal_status(), mimetype='text/event-stream')
Then I'm trying to reveive the code in js from the response like this:
<script>
var source = new EventSource("/progress");
source.onmessage = function(event) {
console.log(event.data);
}
</script>
However nothing appears in the console more than a 200 response message. I've tried casting to str the yield response from signal_status(). If I print the call to signal_status() the number is displayed normaly, so i don't think the threading is the issue.
Am I using the right approach to this issue, or Is there any other way I could display the status of the process in the client?

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.

Categories

Resources