Apache Thrift : Python server with Javascript client - javascript

I'm currently using Apache Thrift for an API project.
I started with a little test project in order to understand how Thrift works. So, I would like to use a python server with a browser-based javascript Client.
I've read the documentation entirely, but I still have an issue I can't resolve :( :
Server output :
127.0.0.1 - - [04/Dec/2018 17:04:34] code 501, message Unsupported method ('OPTIONS')
127.0.0.1 - - [04/Dec/2018 17:04:34] "OPTIONS / HTTP/1.1" 501 -
test.thrift
enum Modulation
{
BPSK
QPSK
APSK16
APSK32
}
struct Coordinate {
1: i32 X,
2: i32 Y
}
struct Constellation {
1: string name,
2: i32 timestamp,
3: list<Coordinate> coordinates
}
service Dealer
{
Constellation getConstellation()
Modulation getModulation()
void setModulation(1: Modulation new_modulation)
i32 getTimestamp()
}
server.py
import glob
import sys
sys.path.append('gen-py')
from TApp import Dealer
from TApp.ttypes import *
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import *
from thrift.server import TServer, THttpServer
import time
class DealerHandler:
def __init__(self):
self.modulation = Modulation.BPSK
def getConstellation(self):
c = Constellation()
c.name = "Test"
c.timestamp = self.getTimestamp()
c.coordinates = []
return c
def getModulation(self):
return self.modulation
def setModulation(self, new_modulation):
self.modulation = new_modulation
def getTimestamp(self):
return int(str(time.time()).split('.')[0])
if __name__ == '__main__':
handler = DealerHandler()
processor = Dealer.Processor(handler)
port = 9090
host = '127.0.0.1'
# HTTP SERVER
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TJSONProtocol.TJSONProtocolFactory()
# List of all protocols : https://thrift-tutorial.readthedocs.io/en/latest/thrift-stack.html
#server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
server = THttpServer.THttpServer(processor, (host, port), pfactory)
server.serve()
index.html
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
<div id="timestamp" style="margin:auto; width:70%; padding:15px; text-align:center; border:1px solid black;">
No Value
</div>
<br />
<button type="button" name="button" class="btn btn-info" style="width:100%" onclick="update_timestamp()">Start connection</button>
</body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" charset="utf-8"></script>
<script src="thrift.js" charset="utf-8"></script>
<script src="test_types.js" charset="utf-8"></script>
<script src="Dealer.js" charset="utf-8"></script>
<script type="text/javascript">
function update_timestamp() {
var transport = new Thrift.TXHRTransport("http://localhost:9090");
var protocol = new Thrift.TJSONProtocol(transport);
var client = new DealerClient(protocol);
var val = client.getTimestamp();
document.getElementById("timestamp").innerHTML = val;
}
</script>
</html>

Related

Unable to run a js script using onClick property of js

I am trying to run a python script. I have an input field in html which will pass the values to js file. Then I used python-shell to pass the values in a form of arguments to the python script to execute them. I am using express.js for scripting
Here is my temp.ejs file
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="./index.js"></script>
<title>Document</title>
</head>
<body>
<img src="./my_plot.png">
<form>
<input type="text" id="source" />
<button onclick="get_data();">Go!</button>
</form>
</body>
</html>
Index.js
function get_data() {
var source = document.getElementById("source").value;
alert(source);
var options = {
args: [source],
pythonPath: '/usr/bin/python3'
};
var tests = new PythonShell('hello.py', options);
tests.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
}
python file
import matplotlib.pyplot as plt
import numpy as np
import wave
import sys
CHANNELS = 2
swidth = 4
Change_RATE = 2
T = int(sys.argv[1])
#print(source)
q = 0.5
Q = 1/10
A = 1 # amplitude of signal # quatization stepsize
N = 2000
spf = wave.open('sample.wav', 'rb')
RATE=spf.getframerate()
Byte = spf.getsampwidth()
signal = spf.readframes(1024)
signal = np.fromstring(signal, 'Int16')
def uniform_midtread_quantizer(x, Q):
# limiter
x = np.copy(x)
idx = np.where(np.abs(x) >= 1)
x[idx] = np.sign(x[idx])
# linear uniform quantization
xQ = Q * np.floor(x/Q + 1/2)
return xQ
def plot_signals(x, xQ, T):
e = xQ - x
plt.figure(figsize=(10,6))
plt.plot(signal, label=r'quantized signal $x_Q[k]$')
plt.xlabel(r'$k$')
plt.axis([0, N, -T, T])
plt.grid()
plt.savefig('my_plot.png')
# generate signal
x = signal
# quantize signal
xQ = uniform_midtread_quantizer(x, Q)
# plot signals
plot_signals(x, xQ, T)
When I am doing node index.js in terminal then I am getting the desired output but not when I pass the value through html (so no error with python and js file)
Express.js is not causing the error as i have used vanilla ja also but same error occured

do I need to install plotly even though I am calling cdn in html?

I am using flask to build online app. I am grabbing user input using d3.js then send it off to app.py which will use this input to make an api call and grab appropriate data then it will return jsonfied data back to javascript for rendering plot in correct html tag however it keeps on giving me error: Error: DOM element provided is null or undefined
app.py:
import os
from flask import Flask, render_template, jsonify, request, redirect, url_for
from alpha_vantage.timeseries import TimeSeries
import plotly
# import plotly.plotly as py
# import plotly.graph_objs as go
app = Flask(__name__)
api_key = "ssdqwjhwq"
# This will run upon entrance
#app.route("/")
def home():
return render_template("index.html")
#app.route("/stockchart/<label>")
def stock_data(label):
ts = TimeSeries(key=api_key, output_format='pandas')
df, meta_deta = ts.get_daily(label, outputsize="full")
df.columns = ["open", "high", "low", "close", "volume"]
data = [{"dates":list(df.index.values)},
{"close": list(df.close)}]
return jsonify(data)
if __name__ == "__main__":
app.run()
my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Stock Screener</title>
<!-- Importing all cdn -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.5.0/d3.min.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="text-center">
<h2>Stock Screener</h2>
<h5>Interactive chart with predictions using machine learning</h5>
</div>
<div>
<!-- Input for stock label -->
<form>
<label for="stockInput">Enter stock label</label>
<!-- use js to store input into a variable. -->
<input type="text" id="stockInput" name="stock_label" placeholder="Label">
<!-- submit button-->
<input type="submit" value="submit" id="stocklabelsubmit">
</form>
</div>
<div class="chart">
</div>
</body>
<script src="../static/js/index.js"></script>
</html>
And my javascript
// give reference to submit button
// Upon click, submitted function will run
d3.select("#stocklabelsubmit").on("click", submitted);
function submitted(){
d3.event.preventDefault();
// grab label inputted.
var inputted_label = d3.select("#stockInput").node().value;
// refresh input box
d3.select("#stockInput").node().value = "";
// pass inputted_label to plot function
Plot(inputted_label);
};
function Plot(input){
var url = `/stockchart/${input}`
// when this function is called call /stock_data function!!
// data is what is returned from python
d3.json(url).then(function(data){
console.log(data);
console.log(data[0]);
console.log(data[0].dates);
var trace = {
x:data[0].dates,
y:data[1].close,
type: "scatter"
};
var layout {
title:"Stock chart",
xaxis:{
title:"dates"
},
yaxis:{
title:"closing price"
}
};
var data = [trace];
// var loc_plot = document.getElementById("chart");
Plotly.newPlot("chart", data, layout);
});
};
Error tells me that there is an error in js line 33 = Plotly.newPlot("chart", data,layout); I am not sure how I can fix this everything seems to work fine until plotting as it console logs properly. Any help? Thanks!
According to the documentation, the graphDiv argument of Plotly.newPlot() refers to either a DOM node or string ID of a DOM node.
In your code above, it looks like you are providing neither. You are providing the class of a DOM node, but not an actual DOM node or ID of a DOM node. This probably explains the error you're getting regarding the null or undefined DOM node.
Try changing <div class="chart"> to <div class="chart" id="chart"> (or some other ID), or get the node using Element.querySelector() and pass that in for the DOM node instead and see if that works.

How to save matplotlib figure to jpeg file from javascript request?

I'm developing a web application in linux environnement to display image of data array.
So i would like to save images from python plot to jpeg files to be able to display them in a browser. Python code works correctly when executed from the console. But if called with a javascript request it hangs due to plt use, even with pltioff(). done message is send if i remove all plt code.
python :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
import os
import json
curr = os.getcwd()
plt.ioff()
fig, ax = plt.subplots( 1 )
ax.plot([1, 2, 3])
plt.show()
fig.savefig(curr+"/"+'test.jpeg',dpi=224,quality=50)
messJ = json.dumps( "done" )
print('Content-type: text/html')
print("\n")
print "%s" %messJ
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>my page</title>
</head>
<body >
<input type="button" id="plotsrv" value="plotsrv" />
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="pythonplot.js"></script>
javascript :
document.getElementById('plotsrv').addEventListener('click', trait_Vdatasrv, false);
function trait_Vdatasrv (e) {
var url = 'pyplot.py';
console.log("url:"+url);
$.post(url,{ file:'ncfile' }, function(data){
$('#data').html(data);
console.log("data"+data);
var jsdec=JSON.parse(data);
console.log(jsdec); }
); }
Regards
I finally found ,
it is needed to add matplotlib.use('Agg')
to avoid display output

getting the status of arduino digital pins in webpage

I want to read the status of my digital pins of arduino and want to display it
in web page. For web programming i am using Flask. I tried this code but its not working. from arduino side I am reading the values of 6 digital pins in the form of 1 and 0. How i can do this? Any help would be appreciated.
<!doctype html>
<html>
<head>
</head>
<body>
<h1 style="font-size:30px;font-family:verdana;"><b>STATUS READ </h1><br><br>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p id="#status1"></p>
<p id="#status2"></p>
<p id="#status3"></p>
<p id="#status4"></p>
<p id="#status5"></p>
<p id="#status6"></p>
<script type=text/javascript>
function updatevalues() {
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.getJSON($SCRIPT_ROOT+"/a",
function(data) {
$("#status1").text(data.m+" %")
$("#status2").text(data.n+" %")
$("#status3").text(data.o+" %")
$("#status4").text(data.p+" %")
$("#status5").text(data.q+" %")
$("#status6").text(data.r+" %")
});
}
</script>
</body>
</html>
Python code:
from flask import Flask, render_template,request,redirect, url_for,jsonify,flash
import flask
from shelljob import proc
import math
import eventlet
eventlet.monkey_patch()
from flask import Response
import serial
import time
from datetime import datetime
import json
import random
from flask.ext.bootstrap import Bootstrap
from flask_bootstrap import WebCDN
app = flask.Flask(__name__)
app.secret_key = 'some_secret'
bootstrap = Bootstrap(app)
app.extensions['bootstrap']['cdns']['jquery'] = WebCDN('//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/')
arduino= serial.Serial( '/dev/ttyACM0' , 9600) #creating object
#app.route('/')
def home():
return render_template('status.html')
#app.route('/a',methods=['GET'])
def a():
mydata=arduino.readline().split(',')
return jsonify(m=float(mydata[0]),n=float(mydata[1]),o=float(mydata[2]),p=float(mydata[3]),q=float(mydata[4]),r=float(mydata[5]))
if __name__ == "__main__":
app.run()
It seems like you're not calling updatevalues in Javascript. You should try with something like this:
setInterval(updatevalues, 1000); //So it runs the function every 1000ms (1 second)

Socket.js not working with RaspberryPi

I am trying to create a flask application to automatic generator of random string. I would like to implement with socket.js. So everything going nice except the connection with the of socket. It's worked with the PC but not working with raspberry Pi.
Here is the files structure
|-- app.py
|-- static
| `-- js
| |-- ajax.js
| |-- hello_world.js
| `-- Socket.js
`-- templates
`-- hello_world.html
Here is my code samples.
app.py
from flask import Flask,render_template
from flask.ext.socketio import SocketIO, emit
import random
import string
app = Flask(__name__)
socketio = SocketIO(app)
class AppObject():
def __init__(self):
self.app = Flask(__name__)
self.socketio = SocketIO(self.app)
#app.route('/')
def Hello():
global appObject
sampleText = appObject.stringGen()
return render_template('hello_world.html', name=sampleText)
def stringGen(self):
chars = "".join( [random.choice(string.letters) for i in xrange(15)] )
return chars
if __name__ == '__main__':
appObject = AppObject()
appObject.socketio.run(app,host="0.0.0.0", debug=True)
hello_world.js
$(document).ready(function() {
namespace = '/test';
var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
var b1 = document.getElementById('text-id');
});
hello_world.html
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="static/js/ajax.js"></script>
<script src="static/js/hello_world.js"></script>
<script type="text/javascript" src="static/js/Socket.js"></script>
<script type="text/javascript" language="javascript"></script>
</head>
{% if name %}
<h1 id="text-id"> {{ name }}!</h1>
{% else %}
<h1>Hello World!</h1>
{% endif %}
</html>
Here is my error
When i implementing all these i am getting an error TypeError: a.transport is null in socket.js. And it's point to the line which is used to connect socket in JavaScript (var socket = io.connect('http://' + document.domain + ':' + location.port + namespace); ). I checked with another PC via ssh.But it's worked fine I don't know why. Please help to solve this issue.
Thank you.

Categories

Resources