ODOO: How to call python function from javascript [duplicate] - javascript

I'd like to call a Python function from JavaScript code, because there isn't an alternative in JavaScript for doing what I want. Is this possible? Could you adjust the below snippet to work?
JavaScript code:
var tag = document.getElementsByTagName("p")[0];
text = tag.innerHTML;
// Here I would like to call the Python interpreter with Python function
arrOfStrings = openSomehowPythonInterpreter("~/pythoncode.py", "processParagraph(text)");
~/pythoncode.py contains functions using advanced libraries that don't have an easy to write equivalent in JavaScript:
import nltk # is not in JavaScript
def processParagraph(text):
...
nltk calls
...
return lst # returns a list of strings (will be converted to JavaScript array)

All you need is to make an ajax request to your pythoncode.
You can do this with jquery http://api.jquery.com/jQuery.ajax/, or use just javascript
$.ajax({
type: "POST",
url: "~/pythoncode.py",
data: { param: text}
}).done(function( o ) {
// do something
});

From the document.getElementsByTagName I guess you are running the javascript in a browser.
The traditional way to expose functionality to javascript running in the browser is calling a remote URL using AJAX. The X in AJAX is for XML, but nowadays everybody uses JSON instead of XML.
For example, using jQuery you can do something like:
$.getJSON('http://example.com/your/webservice?param1=x&param2=y',
function(data, textStatus, jqXHR) {
alert(data);
}
)
You will need to implement a python webservice on the server side. For simple webservices I like to use Flask.
A typical implementation looks like:
#app.route("/your/webservice")
def my_webservice():
return jsonify(result=some_function(**request.args))
You can run IronPython (kind of Python.Net) in the browser with silverlight, but I don't know if NLTK is available for IronPython.

Communicating through processes
Example:
Python: This python code block should return random temperatures.
# sensor.py
import random, time
while True:
time.sleep(random.random() * 5) # wait 0 to 5 seconds
temperature = (random.random() * 20) - 5 # -5 to 15
print(temperature, flush=True, end='')
Javascript (Nodejs): Here we will need to spawn a new child process to run our python code and then get the printed output.
// temperature-listener.js
const { spawn } = require('child_process');
const temperatures = []; // Store readings
const sensor = spawn('python', ['sensor.py']);
sensor.stdout.on('data', function(data) {
// convert Buffer object to Float
temperatures.push(parseFloat(data));
console.log(temperatures);
});

Typically you would accomplish this using an ajax request that looks like
var xhr = new XMLHttpRequest();
xhr.open("GET", "pythoncode.py?text=" + text, true);
xhr.responseType = "JSON";
xhr.onload = function(e) {
var arrOfStrings = JSON.parse(xhr.response);
}
xhr.send();

You cannot run .py files from JavaScript without the Python program like you cannot open .txt files without a text editor. But the whole thing becomes a breath with a help of a Web API Server (IIS in the example below).
Install python and create a sample file test.py
import sys
# print sys.argv[0] prints test.py
# print sys.argv[1] prints your_var_1
def hello():
print "Hi" + " " + sys.argv[1]
if __name__ == "__main__":
hello()
Create a method in your Web API Server
[HttpGet]
public string SayHi(string id)
{
string fileName = HostingEnvironment.MapPath("~/Pyphon") + "\\" + "test.py";
Process p = new Process();
p.StartInfo = new ProcessStartInfo(#"C:\Python27\python.exe", fileName + " " + id)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
return p.StandardOutput.ReadToEnd();
}
And now for your JavaScript:
function processSayingHi() {
var your_param = 'abc';
$.ajax({
url: '/api/your_controller_name/SayHi/' + your_param,
type: 'GET',
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
}
Remember that your .py file won't run on your user's computer, but instead on the server.

Despite what some replies and comments suggest, there are a number of ways for using Python on the front-end. For your question in particular, see this reply.

Related

How to pass a variable value from javascript to perl

I'm using a JavaScript plugin to get the IP address. If the IP address starts with 10.15 I want to assign one value to a variable, and if the IP starts with 10.13 I want to assign a different value to the same variable.(I don't know if the variable has to be in Perl or JavaScript)
I'm trying this but is not working.
my $propt = "";
getUserIP(function(ip) {
console.log('IP: ' + ip);
const ips = ip.split('.');
var pro = document.getElementById('property');
console.log(pro);
if (ips[0] === "10" && ips[1] === "15") {
pro.value = "propt1";
To_Here
$propt = "SRC";
print <<"To_Here";
}
else if(ips[0] === "10" && ips[1] === "13") {
pro.value = "propt2";
To_Here
$propt = "ACC";
print <<"To_Here";
}
else {
pro.value = "propt";
To_Here
$propt = "TAP";
print <<"To_Here";
}
console.log(pro);
First I tried passing the value to an HTML input and reading the value of the input but I don't know if this is possible in Perl
<input id="property" type="hidden" name="property" value=""/>
The final step of what I'm trying to do is to run a query based on the property
$ql = "Select from properties where property = '?????' <----
On the JavaScript side you will need to send a GET request to the Perl script. I've only done this using jQuery (see docs) so you'll need to adapt this if you want a pure JavaScript solution:
function getUserIp(ips) {
var ipString = ips.join(';');
$.ajax({
type: 'GET',
url: '/path/to/script.pl',
data: { user_ips : ipString },
statusCode: {
200: function(data, textStatus, jqXHR) {
$('#id').html(jqXHR.responseText);
}
}
});
}
Note that the ips variable should be a string when you pass it to Perl. You can pass an array of params to Perl (see CGI docs), but I've found splitting a string after the fact to be the most reliable.
I'll show how to capture the parameter using Perl CGI because its simple, but if you're planning on making a full website then I strongly recommend using a web framework. There are several for Perl, like Catalyst and Mojolicious, with varying learning curves.
Using Perl's CGI module, you can capture parameters using the aptly-named param() method:
#! perl
use strict;
use warnings;
use CGI;
use CGI::Carp qw(fatalsToBrowser); # just to make it easier to see errors
my $cgi = CGI->new;
my $ip_string = $cgi->param('user_ips');
my #ips = split(';', $ip_string);
my $results;
foreach my $ip (#ips) {
# do whatever here to populate $results
}
# send results back to jQuery
print $cgi->header( -type => 'text/plain', -status => '200' );
print $results;
print $cgi->end_html;
1;
Make sure you add the appropriate header that corresponds to the statusCode in the $.ajax() method and also call end_html() at the end of the Perl script, otherwise the jQuery/JavaScript may not understand/capture the results.

Sending an Array from Python to JS

I am new to python and JS. I am trying to call a python method from a js code. The python code is supposed to do some calculation and returns me the results which is array of arrays (e.g., [[1,3],[3, 5]]). I have looked at few answers such as this. However, I was not able to solve my problem. Below is what I have so far:
JS code : This sends string "start" to my python code.
var a = $.post("/mlModel", {
Ml_list: JSON.stringify("start"),
contentType: "application/json",
dataType: "json"
});
console.log(JSON.parse(a));
Python Code: Python code gets the string "start", does some process, and return the results in the form of array of arrays [[2,4],[2,6]]
enter code here
#app.route('/mlModel', methods = ['POST'])
def get_post_MlModel():
jsdata = request.form['Ml_list']
jsdata = json.loads(jsdata)
jsdata = ast.literal_eval(json.dumps(jsdata))
// I send "start" to calculate method and it returns data = [[2,3],[1,3]]
data = calculate(jsdata)
return json.dumps(data)
When I run this code, this returns me "Unexpected token o in JSON at position 1"
Any idea?
jQuery.post is an asynchronous operation so a isn't ready yet when you try to use the JSON in the response. try using a callback which is called when the request is finished
$.post("/mlModel", {
Ml_list: JSON.stringify("start"),
contentType: "application/json",
dataType: "json"
}).done(function(data) {
console.log("success " + JSON.parse(data));
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error( "failure " + errorThrown );
})
Here's the typical python and javascript code used while sending and receiving objects over the server. The example below sends a string ("start") from the client and returns a list of sequential index pairs as lists.
On the python side:
#app.route('/testQuery', methods=['POST'])
def testQuery():
queryString = request.form['queryString']
outputList = []
for i in range(0,len(queryString)):
char = queryString[i]
outputList.append([i,(i+1)])
return jsonify({
"outputList" : outputList
})
On the javascript side:
$.post("/testQuery", {"queryString": "start"})
.done(function (response) {
console.log(response)
});
Hope that helps.

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

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

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

Addon firefox php request

i'm trying to develop Firefox extension
problem :
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = response.json;
}
});
I want to use this request function to parse json to an array (List here) from php file.
The php my php file echo json form correctly, but I can't transform the data into javascript array to be able to use it in my addon.
if there is a better idea than using this function to do it please tell me :)
try this: MDN - JSON Object
JSON.parse and JSON.stringify
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = JSON.parse(response.json);
}
});
it's very important to use double quotes.
If you are having a problem with JSON.parse. Copy your array to scratchpad and then run JSON.stringify on it and then make sure your php file matches the strignified result.
if Addon-SDK doesnt have JSON then you gotta require the module if there is one. If there isn't one than require('chrome') and grab the component HERE
There's a bug in Noitidarts code.
why JSON.parse the request.json? If you want to parse do it on request.text
However no need to json.parse as the request module tries to parse and if successful retuns request.json
see here:
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=mozhacks&count=1",
onComplete: function (response) {
var tweet = response.json[0];
console.log("User: " + tweet.user.screen_name);
console.log("Tweet: " + tweet.text);
}
});
// Be a good consumer and check for rate limiting before doing more.
Request({
url: "http://api.twitter.com/1/account/rate_limit_status.json",
onComplete: function (response) {
if (response.json.remaining_hits) {
latestTweetRequest.get();
} else {
console.log("You have been rate limited!");
}
}
}).get();
so the likely problem is that your php is not outputting a json string that json.parse can read. make sure to use ". figure out what your php file should return by running json.stringify on a dummy object. ie:
var obj = {myarr:[1,8,9,7,89,0,'ji'],strr:'khhkjh',anothrtObj:{1:45,56:8}};
alert(JSON.stringify(obj)) //{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
so now in your php make sure your outputted text mateches this format
{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
if your php outputs something like below JSON.parse will fail on it so request.json will be null
{myarr:[1,8,9,7,89,0,"ji"],strr:"khhkjh",anothrtObj:{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,"ji"],'strr':"khhkjh",'anothrtObj':{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,'ji'],'strr':'khhkjh','anothrtObj':{'1':45,'56':8}}

Categories

Resources