How to communicate with python server from web browser? - javascript

I'm trying to send basic commands to a robot from a webbrowser.
The robot is connected to my network and it is running a simpleXMLRPC server as below:
import socket
from xmlrpc.server import SimpleXMLRPCServer
message = []
def py_setMsg(msg):
#global message
message.append(msg)
return "check"
def py_getMsg():
if len(message) > 0:
temp = str(message[-1])
message.pop(-1)
return temp
else:
return "(no message)"
hostname = socket.gethostname()
host = socket.gethostbyname(hostname)
port = 60050
server = SimpleXMLRPCServer((host, port))
server.register_function(py_setMsg, "ext_setMsg")
server.register_function(py_getMsg, "ext_getMsg")
print("XMLRPC Server started..")
server.serve_forever()
My robot checks the messages in the message list and executes the commands in the list one by one.
What I want is to be able to add these commands from a web browser. So basically I want a command to be added to the list in my python server when a button is pressed, something like this:
<html>
<head>
</head>
<body>
<button type="button" onclick="setMessage()">klik hier</button>
<script>
function setMessage(){
send command to my python server
}
</script>
</body>
</html>
Can anyone tell me how I can achieve this?

Related

Send a variable from a python file, to javascript, and then to a separate HTML file?

I'm trying to create a chrome extension, with the main code being in python but I'm struggling. I've succeeded in sending information from the user inputted from the HTML side to the python script, but not the other way around. Here's what I have so far (or the code that seems to be the problem):
Python:
#app.route('/get_data', methods = ['POST'])
def get_data():
taken = request.get_data()
taken2 = taken.decode()
print(taken2)
strength = int(taken2) #this works, I use this later in the code
my_variable = 5 #just for example
return jsonify(my_variable), 200
background.js (javascript)
function myAction(input) {
console.log("input value is : " + input.value);
newish = input.value
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xxhttp.open("POST", "http://127.0.0.1:5000/get_data");
xxhttp.send(newish);
//so sending newish here works, this shows up on my python console (strength becomes this)
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css">
<script src="background.js" type="text/javascript">
</script>
</head>
<body>
<h1>A Thing!</h1>
<div style="padding: 20px 20px 20px 20px;">
<h3>Hello,</h3>
<p>User input please? : </p>
<input id="name_textbox" />
<button id="ok_btn" type="button">OK</button>
</div>
</body>
</html> stuff
What I'm aiming for is for the my_variable to be accepted into the javascript file somehow, and then the html being able to access and display the contents of my_variable. I've tried looking around, but nowhere seems to have the exact thing I'm looking for (send python variable to separate html file for chrome extension). I'm at a bit of a loss, any help would be greatly appreciated, thanks!
Better way of doing it
Since you want to send the variable from python to html by reading the file, this is better than using the FS module in javascript.
example index.html code:
<body>
<h1>Hello, {first_header:}!</h1>
<p>{p2:}, {p1:}</p>
</body>
python code for the above:
newFileCode = open("index.html", "r").read().format(first_header='goodbye',
p1='World',
p2='Hello')
open("index.html", "w").write(newFileCode)
output in the HTML file:
<body>
<h1>Hello, goodbye!</h1>
<p>Hello, World</p>
</body>
read more about file handling in python here
PREVIOUS ANSWER
You can parse the data using JSON. Although, you'll need a new Node.js module fs https://nodejs.org/api/fs.html.
Once you've installed that module, you have to maintain two JSONs, one being a JS variable and the other being an external .json file.
Use this code to write in external JSON files in javascript:
fs = require('fs');
var name = 'fileName.json';
var m = {"example": "HELLO"}
fs.writeFileSync(name, JSON.stringify(m));
Use this code to read an external JSON file in javascript:
JSON.parse(fs.readFileSync(name).toString())
To get/read the data from the external JSON file in python use this code:
import json
# Opening JSON file
f = open('fileName.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data['emp_details']:
print(i)
# Closing file
f.close()
You can edit the file from javascript and can read it in python using a while loop

Execute Javascript of an email sended with python smtplib

I'm practicing emailing and I wanted to know if it's possible to execute Javascript code when you send and email using smtplib and email libs, and when your message contain HTML code ?
It seem that nothing append.
HTML file :
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
</div>
<p class='Test'>This is my first sentence</p>
<script type="text/javascript">
var list = document.querySelector('p.Test');
list.innerHTML = "I want to change it";
</script>
</body>
</html>
Python Code:
import smtplib
from email.message import EmailMessage
def ConnectServer(User, Pass, Host):
SMTPServer = smtplib.SMTP_SSL(Host)
SMTPServer.ehlo()
SMTPServer.login(User, Pass)
return SMTPServer
def SendMail(Server, src, dst, data):
msg = EmailMessage()
msg['From'] = src
msg['To'] = dst
msg['Subject'] = 'Test envoi python'
msg.add_alternative(data, 'html')
Server.send_message(msg, src, dst)
def main():
#Define email adresses
me = 'AN_EMAIL#MAIL.com'
me2 = 'AN_OTHER_EMAIL#mail.com'
Server = ConnectServer(me, 'PASS', 'smtp.gmail.com')
with open('HTML PATH HERE', 'r', encoding='utf8') as File:
data = File.read()
SendMail(Server, me, me2, data)
pass
if __name__ == '__main__':
main()
I hope it's clear.
As far as i know we cant , i also tried to do this, i wanted to include a search bar for the table content in mail.
"No. JavaScript won't work in mails. A cool way to implement this feature
would be to include an image that points to your server, where you generate
the weather report server side and render it as an image, and return it to
the client.
Note though that Gmail caches images and depending on when he does it that
might not be refreshed."
Source : https://www.quora.com/

Dynamically get web socket URL

I have a Play 2.5 application that uses a web socket. In my Controller I establish it as
def socket = WebSocket.accept[JsValue, JsValue] { request =>
ActorFlow.actorRef(out => TroiWebSocket.props(db, out, comm.communicator, system))
}
And, it's accessed in my routes as
GET /push-notifications controllers.Application.socket
As, currently, my application is running locally, I can reference the socket in a javascript file using
var socket = new WebSocket("ws://localhost:9000/push-notifications");
However, I'm starting to move my stuff away from the localhost, and need a way to reference the url in my javascript file. This URL might change (and could be different depending on the development environment). So, how can I reference this URL dynamically? That is, how do I say
var socket = new Websocket(URL_OF_WEBSOCKET)
I thought of breaking it up in my config files and trying to do it that way, but I'm not so sure that would work.
Any and all help would be appreciated.
If you are using plain javascript. Declare a File config.js and define some global Object with some config data.
<html>
<head>
<script>
var config = {
"localWSUrl" : "ws://localhost:9000/socket",
"wsUrl" : "ws://serverurl.com:443/socket"
}
</script>
<script>
console.log(config.wsUrl);
</script>
</head>
<body>
</body>
</html>
For simplicity sake I wrote everything in one file. You would exclude the config part and import the file via the script tag's src attribute. And then you can reuse it where you need it.
If the URL to get main page of your application is the same or partially same to connect websocket, suppose:
Url app: myapp.com
Websocket url: myapp.com/push-notification
So you could do in your js file using window.location of js standard api
var tcp = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
var host = window.location.host;
var path = '/push-notification';
var ws = new WebSocket(tcp+host+path);
Something like that..
I hope It helps.

Apache Thrift Javascript client to C++ Server [duplicate]

I have the following Thrift client code in javascript:
<script language="javascript" type="text/javascript" src="thrift.js" />
<script language="javascript" type="text/javascript" src="QuantSvc_types.js" />
<script language="javascript" type="text/javascript" src="QuantSvc.js" />
<script language="javascript" type="text/javascript">
function calc() {
var transport = new Thrift.Transport("http://localhost:9997/QuantSvc/");
var protocol = new Thrift.Protocol(transport);
var client = new QuantSvcClient(protocol);
try {
result = client.ListAllVariables()
} catch(ouch) {
alert("An exception occurred!")
}
}
</script>
Which is triggered when I push a button on my HTML page. Then, I have the following server-side Scala code, running on localhost:9997:
object Application extends App {
val handler = new QuantSvcHandler()
val processor = new QuantSvc.Processor(handler)
val serverTransport = new TServerSocket(9997)
val server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor))
}
Where the QuantSvcHandler's ListAllVariables function is (basically a skeleton function, just trying to get things to work):
override def ListAllVariables(): util.List[Attributes] =
{
var input = scala.collection.mutable.Buffer[Attributes]()
input
}
I put a breakpoint at the first line of ListAllVariables, and also a few places in the QuantSvcHandler processor. I run the server in debug in intellij IDEA, open my HTML page in Chrome, and push the button (the one that calls the javascript calc() function). The button stays stuck and I see no kind of response on the server, the breakpoints aren't being hit.
Any ideas about what I'm doing wrong?
You mix a HTTP client with a socket server.
Although HTTP uses sockets, the Thrift HTTP transport is not compatible with the Thrift Sockets transport. You need to set up the exact same protocol/transport stack on both ends. The only exception to that rule is that some server transports implicitly require an additional framed transport layer on the client side.
So the solution is to use a HTTP server. Depending on the version you use, you may also have to switch to the JSON protocol.

notepad++ with node using sockets error

Im trying to send a message from a webpage to a node server. Im using notepad++. My html looks likes this:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
<script>
function one()
{
var socket = io.connect('http://192.168.201.91:8001');//connect the socket to url
socket.emit('Stream', {"StreamName": "Livestream1"});//send the socket with the parameter and data
}
</script>
</head>
<body>
</br>
</br>
<center><button type ="Button" onclick="one()">Stream name 1</button></center>
</body>
</html>
These are supposed to connect to a node server which is on the given address.
In node I have set up the sockets like this:
var io_client = require('socket.io').listen('8001');
io_client.on('Stream', function(data)
{
var name = data;
console.log(data);
});
Do I need to use socket.io-client for this to get a message from the html to the server and the server to listen??
Any help would be great
There were two problems in your question.
1.) Use latest version of socket-io client. Older leads to bad request error. use following
<script src="https://cdn.socket.io/socket.io-1.0.6.js"></script>
2.) your code in server should be like this.
var server = require('socket.io').listen('8001');
server.on('connection',function(socket){
console.log('connection');
socket.on('Stream', function(data){
var name = data;
console.log(data);
});
});
You were expecting the Streams event on server itself. But it'll occur on that socket from where it has been sent.

Categories

Resources