Calling python function in server from local machine using angularjs - javascript

I am having problem in calling a python function with angularjs $http request.
I am having a python function which is on server like this
import cgi, cgitb
data= cgi.FieldStorage()
name = data.getvalue("name");
age = data.getvalue("age");
def printinfo( name, age ):
print "Name: ", name
print "Age ", age
return name,age
and i've also included cgi and my javascript code is
angular.module('app1',[])
.controller('ctrl',['$scope','$http' ,function ($scope,$http) {
$scope.bin = 'examp';
$scope.go = function () {
var url = "http://localhost/dump/test/test.py";
var bad =$http({
url :url ,
method:'POST',
data:{"name":"kumar" , "age":21}
}).success(function(data){
alert("working");
});
}
}])
and my javascript code is able to make a call to http://localhost/dump/test/test.py but it is shown as a document even when i included cgi in it ..
Please guide me and also can you guys tell me is it the right way to send the values to server ie can i invoke the function print info by just sending name and age or should i send the function name too. If yes let me know how can i pass it ..
Thanks in advance..

May be your webserver do not know how to handle .py files. You need to configure webserver to handle python. Try the below if it is not configured.
https://www.linux.com/community/blogs/129-servers/757148-configuring-apache2-to-run-python-scripts
But a more good approach is to create a web app using some python framework and expose urls via a web server. If you are interested in that then I would recommend you to learn flask python framework.

Related

Python output on HTML page

I have a python program and I want to print the output of that program on an HTML page using Node JS. The python script is being called using 'child_process'. I want to print the value of 't' on HTML page. Is there any way to do it?
script.py
import time
t=0
def main():
while 1:
t =t+1
print t
time.sleep(2)
# Start process
if __name__ == '__main__':
main()
Here I want to print the value of 't' after every 2 seconds.
app.js
var sys =require('sys');
var myPythonScript ="script.py";
var path =resolve("C:\\Python27\\python.exe");
var pythonExecutable = path;
const spawn = require('child_process').spawn;
const scriptExecution = spawn(pythonExecutable, [myPythonScript]);
scriptExecution.stdout.on('data', (data) => {
console.log(data);
});
});
This JS function is called when a button is clicked on the HTML page.
I have an idea for you- you can create a simple flask app (http://flask.pocoo.org/), that will listen to a specific port.
When this app will receive a REST API request, it will execute your's python code and return the result as a response.
In the javascript side, you will only need to create an ajax request which will provide the request to the flask app.
In this way, you can mix both python and javascript comfortably.
you can use urllib to send the output of your .py file :
import urllib
output="test"
url="post.php"
param=urllib.urlencode({'output':output})
urllib.urlopen(url,param)
to get the post in PHP :
<?php
$output = $_POST["output"];
echo $output;
?>
to get the post parameter in Node.js you can read this :
https://scotch.io/tutorials/use-expressjs-to-get-url-and-post-parameters
How do you extract POST data in Node.js?
https://dzone.com/articles/get-post-parameter-nodejs
Yes, you can code on python then using rapydscript and npm you can convert python code to Js code and it will print on the HTML page. The best part of rapydscript is, it doesn't need any server.
For example:
Below code is an alert function in python:
def greet():
alert("Hello World!")
This will convert to below Js code:
function greet() {
alert("Hello World!");
}
https://www.npmjs.com/package/rapydscript-ng

How to Call Variable from Java to HTML?

I would like to call some variable (code and name -- String) from java class on html class (<label>). And I wonder whether it can be directly applied (without using jsp)? Or it necessary to use javascript?
And if it requires javascript I have added the code below, but it's not working.
<script type="text/javascript">
document.getElementById("lists").innerHTML = name;
</script>
And also this is my java file that store variable code and name.
List<Names> nameList = Common.getNameList(data.getName());
for (int i = 0; i < nameList.size(); i++) {
System.out.println(nameList.get(i).code + "=" + whsList.get(i).name);
}
And in HTML I had,
<div id="lists">
<label>Code<label>
<label>Name<label>
</div>
Please help. Thank you.
No, you can't directly. JavaScript is executed on the client side (browser)
JavaScript is client side scripting lang. and 'Java' run on server side. so you need to send request to server . if you want to use java lang on server side then we need to use servlet or framework like a spring, struts etc.
if you want to use java variable in client side JavaScript then send request to server. you can send request using ajax and send nameList in JSON type from servlet as response then all list available to use in JavaScript ... so you need to refer some example like ...
new link i hope this help
http://www.technicalkeeda.com/jquery/spring-framework-jquery-ajax-request-and-json-response-example

Convert Javascript dictionary to python dictionary

Somewhere in my Django app, I make an Ajax call to my view
$.post("/metrics", {
'program': 'AWebsite',
'marketplace': 'Japan',
'metrics': {'pageLoadTime': '1024'}
});
in my python code, I have got
#require_POST
def metrics(request):
program = request.POST.get('program', '')
marketplace = request.POST.get('marketplace', '')
metrics = request.POST.get('metrics', '')
reportMetrics(metrics, program, marketplace)
the metrics() function in python is supposed to call reportMetrics() with these parameters which are then supposed to go in a log file. But In my log file, I do not see the 'pageLoadTime' value - probably because it is being passed in as a dictionary. In future I need to add more items to this, so it needs to remain a dictionary (and not a string like first two).
Whats the easiest way to convert this incoming javascript dictionary to python dictionary?
Send the javascript dictionary as json and import the python json module to pull it back out. You'll use json.loads(jsonString).
Edit - Added example
$.post("/metrics", {
data: JSON.stringify({
'program': 'AWebsite',
'marketplace': 'Japan',
'metrics': {'pageLoadTime': '1024'}
})
});
Then on the python side
import json
def metrics(request):
data = json.loads(request.POST.get('data'))
program = data.get('program','')
marketplace = data.get('marketplace','')
metrics = data.get('metrics','')
I don't really have a good way of testing this right now, but I believe it should work. You may also have to do some checking if a field is blank, but I believe .get() will handle that for you.

How to connect Javascript to Python sharing data with JSON format in both ways?

I'm trying to find out how to create a local connection between a Python server and a Javascript client using the JSON format for the data to be retrieved. Particularly, I need to make some queries on the HTML client side, send these queries to the server on JSON format and run them on the Python server side to search for data on a SQLite Database. And after getting the results from the database, send those results back to the client in JSON format too.
By now, I just can run the query on Python and code it on JSON like this:
import sqlite3 as dbapi
import json
connection = dbapi.connect("C:/folder/database.db")
mycursor = connection.cursor()
mycursor.execute("select * from people")
results = []
for information in mycursor.fetchall():
results += information
onFormat = json.dumps(results)
print(onFormat)
I know this code does something alike (in fact it runs), because it calls a service on a server which returns data in JSON format (but the server in this example is NOT Python):
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="images"></div>
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: "mount rainier",
tagmode: "any",
format: "json"
},
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
});</script>
</body>
</html>
What I need is to know how should I run (locally) the python program to be an available running web-service and how should be the Javascript to retrieve the data from the python server.
I've looking for this on internet everywhere but I didn't find this answer anywhere because the only answers they give are on how to code JSON inside Python or inside Javascript but not connecting both. Hope somebody can help me on this!!!
Here's a "hello world" example of a flask web-application that can serve static html and javascript files, search database using parameter from a javascript request, and return results to javascript as json:
import sqlite3
from flask import Flask, jsonify, g, redirect, request, url_for
app = Flask(__name__)
#app.before_request
def before_request():
g.db = sqlite3.connect('database.db')
#app.teardown_request
def teardown_request(exception):
if hasattr(g, 'db'):
g.db.close()
#app.route('/')
def index():
return redirect(url_for('static', filename='page.html'))
#app.route('/json-data/')
def json_data():
# get number of items from the javascript request
nitems = request.args.get('nitems', 2)
# query database
cursor = g.db.execute('select * from items limit ?', (nitems,))
# return json
return jsonify(dict(('item%d' % i, item)
for i, item in enumerate(cursor.fetchall(), start=1)))
if __name__ == '__main__':
app.run(debug=True, host='localhost', port=5001) # http://localhost:5001/
else:
application = app # for a WSGI server e.g.,
# twistd -n web --wsgi=hello_world.application --port tcp:5001:interface=localhost
The database setup code is from Using SQLite 3 with Flask.
static/page.html and static/json-jquery.js files are from Ajax/jQuery.getJSON Simple Example, where the javascript code is modified slightly to pass a different url and nitems parameter:
$(document).ready(function(){
$('#getdata-button').live('click', function(){
$.getJSON('/json-data', {'nitems': 3}, function(data) {
$('#showdata').html("<p>item1="+data.item1+" item2="+data.item2+" item3="+data.item3+"</p>");
});
});
});
Your question amounts to "how do I make this python into a webservice".
Probably the most lightweight ways to do that are web.py and flask. Check them out.
If this is getting bigger, consider django with tastypie - that's a simple way to make a json-based api.
Update: Apparently, there is also a python-javascript RPC framework called Pico, to which Felix Kling is a contributor. The intro says:
Literally add one line of code (import pico) to your Python module to
turn it into a web service that is accessible through the Javascript
(and Python) Pico client libararies.
I found finally an easier way than Flask. It's a Python framework called Bottle You only need to download the library from the official web site and put all its files in your working directory in order to import the library. You can also install it using the setup python program included to avoid carrying with the sourcecode everywhere. Then, for making your Web Service Server you can code it like this:
from bottle import hook, response, route, run, static_file, request
import json
import socket
import sqlite3
#These lines are needed for avoiding the "Access-Control-Allow-Origin" errors
#hook('after_request')
def enable_cors():
response.headers['Access-Control-Allow-Origin'] = '*'
#Note that the text on the route decorator is the name of the resource
# and the name of the function which answers the request could have any name
#route('/examplePage')
def exPage():
return "<h1>This is an example of web page</h1><hr/><h2>Hope you enjoy it!</h2>"
#If you want to return a JSON you can use a common dict of Python,
# the conversion to JSON is automatically done by the framework
#route('/sampleJSON', method='GET')
def mySample():
return { "first": "This is the first", "second": "the second one here", "third": "and finally the third one!" }
#If you have to send parameters, the right sintax is as calling the resoure
# with a kind of path, with the parameters separed with slash ( / ) and they
# MUST to be written inside the lesser/greater than signs ( <parameter_name> )
#route('/dataQuery/<name>/<age>')
def myQuery(name,age):
connection= sqlite3.connect("C:/folder/data.db")
mycursor = connection.cursor()
mycursor.execute("select * from client where name = ? and age= ?",(name, age))
results = mycursor.fetchall()
theQuery = []
for tuple in results:
theQuery.append({"name":tuple[0],"age":tuple[1]})
return json.dumps(theQuery)
#If you want to send images in jpg format you can use this below
#route('/images/<filename:re:.*\.jpg>')
def send_image(filename):
return static_file(filename, root="C:/folder/images", mimetype="image/jpg")
#To send a favicon to a webpage use this below
#route('/favicon.ico')
def favicon():
return static_file('windowIcon.ico', root="C:/folder/images", mimetype="image/ico")
#And the MOST important line to set this program as a web service provider is this
run(host=socket.gethostname(), port=8000)
Finally, you can call the REST web service of your Bottlepy app on a Javascript client in this way:
var addr = "192.168.1.100"
var port = "8000"
function makeQuery(name, age){
jQuery.get("http://"+addr+":"+port+"/dataQuery/"+ name+ "/" + age, function(result){
myRes = jQuery.parseJSON(result);
toStore= "<table border='2' bordercolor='#397056'><tr><td><strong>name</strong></td><td><strong>age</strong></td></tr>";
$.each(myRes, function(i, element){
toStore= toStore+ "<tr><td>"+element.name+"</td><td>" + element.age+ "</td></td></tr>";
})
toStore= toStore+ "</table>"
$('#theDataDiv').text('');
$('<br/>').appendTo('#theDataDiv');
$(toStore).appendTo('#theDataDiv');
$('<br/>').appendTo('#theDataDiv');
})
}
I hope it could be useful for somebody else

Passing JavaScript variable to Python

For example:
#!/usr/bin/python
print "This is python."
print "<script type="text/javascript">
var pass_to_python = new Number(7)
</script>"
the_number = pass_to_python???
How do I get the pass_to_python in python?
With pyv8 you can execute javascript from within Python.
import PyV8
class Global(PyV8.JSClass):
pass
with PyV8.JSContext(Global()) as ctxt:
the_number = ctxt.eval("var pass_to_python = new Number(7)")
see http://code.google.com/p/pyv8/
You can GET or POST to the Python script. If you need to do this dynamically, you can use AJAX.
Here is a good link: How are POST and GET variables handled in Python?
i am using flask and ajax to pass values from javacript to python
function pass_values() {
var pass_to_python = new Number(7)
$.ajax(
{
type:'POST',
contentType:'application/json;charset-utf-08',
dataType:'json',
url:'http://127.0.0.1:5000/pass_val?value='+pass_to_python ,
success:function (data) {
var reply=data.reply;
if (reply=="success")
{
return;
}
else
{
alert("some error ocured in session agent")
}
}
}
);
}
python:
#app.route('/pass_val',methods=['POST'])
def pass_val():
name=request.args.get('value')
print('name',name)
return jsonify({'reply':'success'})
HTTP is a simple request-response protocol, it doesn't let you pause mid-stream and wait for more information from the client — and since your JS runs in the browser (JS can run on the server, but most people wouldn't be attempting this if they didn't need the code to run in the browser, so I'm assuming that using server side JS is out of the question) and the Python runs on the server, that is what you need for your code to work (as well as fixing your broken quote nesting in the Python code).
You need to load the complete document, and then issue a new HTTP request.
This might involve having the JS set location.href (making sure you have a fallback for non-JS clients), it might involve using XMLHttpRequest to load new data asynchronously, it might be best using another technique (it is hard to say for sure as your example simplifies too much to tell what X is)
I think using JSON is the best way.you can create a JSON file as intermidiary between JavaScript and Python, both languages can access and modify JSON file

Categories