How do I send data from JS to Python with Flask? - javascript

I'm making a website with Flask and I'd like to be able to execute python code using data from the page. I know that I can simply use forms but it's a single page that is continually updated as it receives user input and it'd be a massive pain in the ass to have it reload the page every time something happens. I know I can do {{ function() }} inside the javascript but how do I do {{ function(args) }} inside the javascript using js variables? So far the only thing I can think of is to update an external database like MongoDB with the js then use Python to read from that, but this process will slow down the website quite a lot.
The jQuery needs to get a list of dictionary objects from the Python function which can then be used in the html. So I need to be able to do something like:
JS:
var dictlist = { getDictList(args) };
dictlist.each(function() {
$("<.Class>").text($(this)['Value']).appendTo("#element");
});
Python:
def getDictList(args):
return dictlistMadeFromArgs

To get data from Javascript to Python with Flask, you either make an AJAX POST request or AJAX GET request with your data.
Flask has six HTTP methods available, of which we only need the GET and POST. Both will take jsdata as a parameter, but get it in different ways. That's how two completely different languages in two different environments like Python and Javascript exchange data.
First, instantiate a GET route in Flask:
#app.route('/getmethod/<jsdata>')
def get_javascript_data(jsdata):
return jsdata
or a POST one:
#app.route('/postmethod', methods = ['POST'])
def get_post_javascript_data():
jsdata = request.form['javascript_data']
return jsdata
The first one is accessed by /getmethod/<javascript_data> with an AJAX GET as follows:
$.get( "/getmethod/<javascript_data>" );
The second one by using an AJAX POST request:
$.post( "/postmethod", {
javascript_data: data
});
Where javascript_data is either a JSON dict or a simple value.
In case you choose JSON, make sure you convert it to a dict in Python:
json.loads(jsdata)[0]
Eg.
GET:
#app.route('/getmethod/<jsdata>')
def get_javascript_data(jsdata):
return json.loads(jsdata)[0]
POST:
#app.route('/postmethod', methods = ['POST'])
def get_post_javascript_data():
jsdata = request.form['javascript_data']
return json.loads(jsdata)[0]
If you need to do it the other way around, pushing Python data down to Javascript, create a simple GET route without parameters that returns a JSON encoded dict:
#app.route('/getpythondata')
def get_python_data():
return json.dumps(pythondata)
Retrieve it from JQuery and decode it:
$.get("/getpythondata", function(data) {
console.log($.parseJSON(data))
})
The [0] in json.loads(jsdata)[0] is there because when you decode a JSON encoded dict in Python, you get a list with the single dict inside, stored at index 0, so your JSON decoded data looks like this:
[{'foo':'bar','baz':'jazz'}] #[0: {'foo':'bar','baz':'jazz'}]
Since what we need is the just the dict inside and not the list, we get the item stored at index 0 which is the dict.
Also, import json.

.html
... id="clickMe" onclick="doFunction();">
.js
function doFunction()
{
const name = document.getElementById("name_").innerHTML
$.ajax({
url: '{{ url_for('view.path') }}',
type: 'POST',
data: {
name: name
},
success: function (response) {
},
error: function (response) {
}
});
};
.py
#app.route("path", methods=['GET', 'POST'])
def view():
name = request.form.get('name')
...

im new in coding, but you can try this:
index.html
<script>
var w = window.innerWidth;
var h = window.innerHeight;
document.getElementById("width").value = w;
document.getElementById("height").value = h;
</script>
<html>
<head>
<!---Your Head--->
</head>
<body>
<form method = "POST" action = "/data">
<input type = "text" id = "InputType" name = "Text">
<input type = "hidden" id = "width" name = "Width">
<input type = "hidden" id = "height" name = "Height">
<input type = "button" onclick = "myFunction()">
</form>
</body>
</html>
.py
from flask import Flask, request
app = Flask(__name__)
html = open("index.html").read()
#app.route("/")
def hello():
return html
#app.route("/data", methods=["POST", "GET"])
def data():
if request.method == "GET":
return "The URL /data is accessed directly. Try going to '/form' to submit form"
if request.method == "POST":
text = request.form["Text"]
w = request.form["Width"]
h = request.form["Height"]
//process your code
return //value of your code

Related

How update data in JavaScript when flask send a josinify response

I am making a project with raspberry Pi, is a control and monitoring data through internet.
Finally I can make the communication with flask-html-JavaScript
In summary I want to update my chart js graph when the flask function response with jsonify data
I am using Ajax method with getjson but I am executing with setinterval and I don’t want to use setinterval, I want that the getjson function execute when flask function response with jsonify data
Exist any method that can make it?
this is my code in flask:
#app.route('/start', methods=['GET', 'POST'])
def start():
n = request.form['number']
print(int(n))
for i in range(int(n)):
GPIO.output(19, GPIO.LOW)
while gt.read_sensor() == 0:
pass
now0 = datetime.now()
for j in range(1):
value = adc.read( channel = 0 )
volt = (value/1023)*3.3
presure = ((volt/3.3)-0.1)*3/2
p1.append(presure)
global pon
pon = presure
time.sleep(0.25)
pon = -100
Here I capture the value sensor and I call update with global variable the function presson:
#app.route('/pon')
def presson():
return jsonify(result = presson)
and this is my javascript code:
var pon = 0;
var test = 0;
function sendData() {
$.ajax({
type: "POST",
url: "{{ url_for('start') }}",
data: { number : $('#number').val() }
});
setInterval(update_values,100);
}
function update_values() {
$.getJSON('/pon',
function(data) {
$('#result').text(data.result);
pon = data.result;
console.log(data)
});
currently that work good, but sometimes the value is not update, then I want that the function getJSON() run only when recieve a correct value (without setInterval method), what recommend me?

How to pass python string to javascript as string in Django?

I have a python string which is javascript code and I want to pass this string to javascript as string too.
My idea is to pass python string to javascript string and then use eval() function in javascript to turn that string to actual code and execute it.
def login(request):
success = '''
window.location = '{% url 'home' %}';
# some other codes
'''
return render(request, "app/login.html", {'success': success})
var code = "{{success}}"
console.log(code) // return Uncaught SyntaxError: Invalid or unexpected token
I have also tried pass the string as json like this
def login(request):
success = '''
window.location = '{% url 'home' %}';
# some other codes
'''
success = json.dumps(success)
return render(request, "app/login.html", {'success': success})
var code = JSON.parse("{{success|safe}}");
console.log(code) //return Uncaught SyntaxError: missing ) after argument list
Last thing that I have tried is
def login(request):
success = '''
window.location = '{% url 'home' %}';
# some other codes
'''
return render(request, "app/login.html", {'success': success})
<h3 id="success_id" hidden>{{success}}</h3>
<script>
var code = $("#success_id").text();
console.log(code) //return window.location = "{% url 'home' %}"
// if i do this
var code = "window.location = '{% url 'home' %}'";
console.log(code) // return window.location = /app/home/
// I want it to return the url like /app/home
</script>
How can I do this?
Ok in essence what you want to do is using Django to pass data to js?
That has to to do with Django creating a Json Response which the JavaScript will then make a request , in essence you are working with some API.
your view code where you wrote the render function won't need that anymore...
Something like
JsonResponse({'success':success})
will be needed , after importing the JsonResponse from 'django.http'
Then at the js file, you will have to use Ajax to call that url with it's required method to get the data needed.
in your script tag , you will then need something like this
const xhr= new XMLHttpRequest ()
xhr.open('django_url', 'method')
xhr.onload = function () {
const msg = xhr.response.success
}
xhr.send()
If you are familiar with fetch or axios you can as well use any library of your choice.
the django_url refers to the url that connects that view
the method refers to the http_method, either a 'GET' or 'POST' (most commonly used) .

flask upload python-base64 image

I'm trying to upload a base64 image (encoded in Python) to my webapp using Flask.
I get the encoded image but get an error when modifying the src of the image element.
Ajax:
$.ajax({
dataType: "json",
type: 'POST',
url: getWebAppBackendUrl("return_cam"),
data: {
image_bytes: img_b64
},
success: function (filter_bytes) {
let data = filter_bytes.heatmap
document.getElementById("cam").src = "data:image/png;base64," + data;
}
});
server side:
#app.route('/return_cam', methods=['GET', 'POST'])
def return_cam():
img_b64 = request.form.get("image_bytes") #get POST data
api_result = client.run_function("returnCAM", image=img_b64)
response = api_result.get("response")
result_dict = json.loads(response)
return json.dumps(result_dict)
The 'data' variable looks like this when printed in the console:
b'ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj...'
and I get ERR_INVALID_URL.
I guess there is some processing to do on this data variable...
Thanks for the help!
Looks like you need to decode that value. Something like:
img_b64 = request.form.get("image_bytes")
img_b64 = img_b64.decode('utf-8')
#...
Not sure if client.run_function will appreciate this, as it's not clear from your question what that method does. Perhaps you could put the above mod within that function if you wrote it yourself, so that the correctly decoded value ends up within response as expected.

Json Ajax Response from Django Application

I have a Django app that the views.py sends a json data to a javascript function on my html. The problem is that I can not access the elements of the data.
I tryied to use JsonParse but not sucess, for instance when I do
var other = JSON.parse(data_doc_pers['data_doc_pers']);
document.getElementById("text_conf4").innerHTML = other['doc_nome'];
I receive the following response: [object Object]
what I am doing wrong???
Here is my code
Views.py
...
json_string = json.dumps({'type_numeric':type_numeric,'type_prop':type_prop,'name':name,'Vinculo':Vinculo,'doc_nome':doc_nome})
return JsonResponse({'data_doc_pers':json_string})
HTML
$.get('{% url "page" %}',{'var':var}, function (data_doc_pers) {
var other = JSON.parse(data_doc_pers['data_doc_pers']);
document.getElementById("text_conf4").innerHTML = other['doc_nome'];
});
Problem solvend!
The error I was doing in javscript was to use var other = JSON.parse(data_doc_pers['data_doc_pers']); the correct should be only (data_doc_pers['data_doc_pers'].

How to send JSON data created by Python to JavaScript?

I am using Python cherrypy and Jinja to serve my web pages. I have two Python files: Main.py (handle web pages) and search.py (server-side functions).
I create a dynamic dropdown list (using JavaScript) based on a local JSON file called component.json(created by function componentSelectBar inside search.py).
I want to ask how can my JavaScript retrieve JSON data without physically storing the JSON data into my local website root's folder and still fulfil the function of dynamic dropdown list.
The componentSelectBar function inside search.py:
def componentSelectBar(self, brand, category):
args = [brand, category]
self.myCursor.callproc('findComponent', args)
for result in self.myCursor.stored_results():
component = result.fetchall()
if (len(component) == 0):
print "component not found"
return "no"
components = []
for com in component:
t = unicodedata.normalize('NFKD', com[0]).encode('ascii', 'ignore')
components.append(t)
j = json.dumps(components)
rowarraysFile = 'public/json/component.json'
f = open(rowarraysFile, 'w')
print >> f, j
print "finish component bar"
return "ok"
The selectBar.js:
$.getJSON("static/json/component.json", function (result) {
console.log("retrieve component list");
console.log("where am i");
$.each(result, function (i, word) {
$("#component").append("<option>"+word+"</option>");
});
});
store results from componentSelectBar into database
expose new api to get results from database and return json to browser
demo here:
#cherrypy.expose
def codeSearch(self, modelNumber, category, brand):
...
result = self.search.componentSelectBar(cherrypy.session['brand'], cherrypy.session['category'])
# here store result into a database, for example, brand_category_search_result
...
#cherrypy.expose
#cherrypy.tools.json_out()
def getSearchResult(self, category, brand):
# load json from that database, here is brand_category_search_result
a_json = loadSearchResult(category, brand)
return a_json
document on CherryPy, hope helps:
Encoding response
In your broswer, you need to GET /getSearchResult for json:
$.getJSON("/getSearchResult/<arguments here>", function (result) {
console.log("retrieve component list");
console.log("where am i");
$.each(result, function (i, word) {
$("#component").append("<option>"+word+"</option>");
});
});
To use that json data directly into javascript you can use
var response = JSON.parse(component);
console.log(component); //prints
OR
You already created json file.If that file is in right format then you can read json data from that file using jQuery jQuery.getJSON() For more: http://api.jquery.com/jQuery.getJSON/
You are rendering a HTML and sending it as response. If you wish to do with JSON, this has to change. You should return JSON in your main.py, whereas you will send a HTML(GET or POST) from Javascript and render it back.
def componentSelectBar(self, brand, category):
/* Your code goes here */
j = json.dumps(components)
// Code to add a persistent store here
rowarraysFile = 'public/json/component.json'
f = open(rowarraysFile, 'w')
print >> f, j
// Better to use append mode and append the contents to the file in python
return j //Instead of string ok
#cherrypy.expose
def codeSearch(self):
json_request = cherrypy.request.body.read()
import json # This should go to the top of the file
input_dict = json.loads(json_request)
modelNumber = input_dict.get("modelNumber", "")
category = input_dict.get("category", "")
brand = input_dict.get("brand", "")
/* Your code goes here */
json_response = self.search.componentSelectBar(cherrypy.session['brand'], cherrypy.session['category'])
return json_response
Here, I added only for the successful scenario. However, you should manage the failure scenarios(a JSON error response that could give as much detail as possible) in the componentSelectBar function. That will help you keep the codeSearch function as plain as possible and help in a long run(read maintaining the code).
And I would suggest you to read PEP 8 and apply it to the code as it is kind of norm for all python programmers and help any one else who touches your code.
EDIT: This is a sample javascript function that will make a post request and get the JSON response:
searchResponse: function(){
$.ajax({
url: 'http://localhost:8080/codeSearch', // Add your URL here
data: {"brand" : "Levis", "category" : "pants"}
async: False,
success: function(search_response) {
response_json = JSON.parse(search_response)
alert(response_json)
// Do what you have to do here;
// In this specific case, you have to generate table or any structure based on the response received
}
})
}

Categories

Resources