Translate simple Perl script into Python that sends a response to client? - javascript

I'm really new to Python and my goal is to have the Python script print something to the client, and then display this on my webpage.
Fortunately, I stumbled upon a small code snippet that does exactly what I want to achieve with Python - unfortunately it is written in Perl.
I was wondering if anyone out there could show me how to write the Perl script in Python?
Here is the link that has all the code: http://www.degraeve.com/reference/simple-ajax-example.php
Here is the Perl script:
#!/usr/bin/perl -w
use CGI;
$query = new CGI;
$secretword = $query->param('w');
$remotehost = $query->remote_host();
print $query->header;
print "<p>The secret word is <b>$secretword</b> and your IP is <b>$remotehost</b>.</p>";
How could I say the same thing in Python?
Here is the HTML page too:
<html>
<head>
<title>Simple Ajax Example</title>
<script language="Javascript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
function getquerystring() {
var form = document.forms['f1'];
var word = form.word.value;
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>
</head>
<body>
<form name="f1">
<p>word: <input name="word" type="text">
<input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/cgi-bin/ajaxTest.pl")'></p>
<div id="result"></div>
</form>
</body>
</html>

Something like this should work.
#!/usr/bin/env python
import cgi
import os
import cgitb; cgitb.enable() # for troubleshooting
form = cgi.FieldStorage()
secretword = form.getfirst("w", "")
remotehost = cgi.escape(os.environ["REMOTE_HOST"] if "REMOTE_HOST" in os.environ else os.environ["REMOTE_ADDR"])
print "Content-Type: text/html"
print # blank line, end of headers
print "<p>The secret word is <b>" + secretword + "</b> and your IP is <b>" + remotehost + "</b>.</p>"
Edit 1: How to list all environment variables.
for k in os.environ.keys():
print "<b>%20s</b>: %s<\br>" % (k, os.environ[k])

Related

how to load data using a javascript

I have almost zero experience with Javascript , I need to use this Javascript in my php script .
<script>
let arr = ["alfa", "beta", "charlie"]
const updateResult = query => {
let resultList = document.querySelector(".result");
resultList.innerHTML = "";
arr.map(algo =>{
query.split(" ").map(word =>{
if(algo.toLowerCase().indexOf(word.toLowerCase()) != -1){
resultList.innerHTML += `<li class="list-group-item">${algo}</li>`;
}
})
})
}
updateResult("")
</script>
This script load the data using
let arr =
However suppose I have all the data specified there in a file in this format
c:/data/mydata.txt
and the data.txt contains data in this form (one data per row)
alfa
bravo
charlie
Now how should I change the javascript above to load the data from c:/data/mydata.txt and not using
let arr = ["alfa", "beta", "charlie"]
?
Thank you
You do not need to change your file, but you cannot use it directly due to security issues. If I would write a Javascript which reads your secret files and you load my page, all your secrets would be revealed, therefore, if you want to load a file, you either have to allow your user to upload it and once the user uploads the file do your logic, or, you can request it via AJAX.
How to upload a file
An example for this is
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
<p id="demo"></p>
<script>
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += "<br><strong>" + (i+1) + ". file</strong><br>";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "<br>";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes <br>";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
</script>
<p><strong>Tip:</strong> Use the Control or the Shift key to select multiple files.</p>
</body>
</html>
source: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_fileupload_files
Getting the file via AJAX
In order to do that, you will need to:
send an AJAX request in your javascript code
parse the request and send back the file via PHP
do your logic in Javascript when the request is responded
Example:
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Download POST Request</title>
</head>
<body>
Enter a text and click the button: <input type="text" id="content" value="Text for the generated pdf">
<button id="download">Send AJAX Request and download file</button>
<script>
document.getElementById('download').addEventListener('click', function () {
var content = document.getElementById('content').value;
var request = new XMLHttpRequest();
request.open('POST', '../server/', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.responseType = 'blob';
request.onload = function() {
// Only handle status code 200
if(request.status === 200) {
// Try to find out the filename from the content disposition `filename` value
var disposition = request.getResponseHeader('content-disposition');
var matches = /"([^"]*)"/.exec(disposition);
var filename = (matches != null && matches[1] ? matches[1] : 'file.pdf');
// The actual download
var blob = new Blob([request.response], { type: 'application/pdf' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// some error handling should be done here...
};
request.send('content=' + content);
});
</script>
</body>
</html>
PHP
<?php
require_once 'vendor/autoload.php';
if($_SERVER['REQUEST_METHOD'] === 'POST') {
header('Content-type: application/pdf');
http_response_code(200);
// Contents
$pdfContent = !empty($_POST['content']) ? $_POST['content'] : 'no content specified';
// Generate the PDOF
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10, $pdfContent);
return $pdf->Output(null, 'foobar-' . time() . '.pdf');
}
// Bad method
http_response_code(405);
exit();
Source: https://nehalist.io/downloading-files-from-post-requests/
You will of course need to modify the code to comply to your needs. Reading a tutorial would not hurt.
you can use ajax for loading data from external file.
a sample of jquery get call is given below. You can also use the same code with your file path and variables.
$("button").click(function(){
$.get("demo_test.php", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
if you are using pure java script instead of jQuery you have to use pure ajax calls.
for more details about jQuery ajax check this link

Live iPerf Output Printed to HTML with PHP/Ajax

I've been working on a web interface for iPerf and it's going pretty well. My goal is to have the output of the commands be streamed live on the page. It works for iPerf2 commands but when I run iPerf3, it only shows the output once the entire test is complete.
Based on my research I've done on this site and others, I'm thinking it might have something to do with the buffer. I've been messing around with flushing the buffer at different times or setting the 'fread' length to different values but I can't get it to act the same as regular iperf commands. I think this because instead of running the 'popen' on the iperf command itself, I used popen on a python script that would run the iperf command. This still returned the same issue. It only shows the output on the web page once the entire test is complete.
Here is my code:
phpQ.php
<!DOCTYPE html>
<html>
<body>
<div>
Server Domain/IP Address: <input id="address" type="text"><br>
<input id="run" type="button" value="iPerf"><br><br>
</div>
<div id="result"></div>
<script>
function updateText(address) {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (this.readyState == 3) {
var old_value = document.getElementById("result").innerHTML;
document.getElementById("result").innerHTML = this.responseText;
}
};
if (purpose == 1) {
var url = 'ajaxQ.php?address='+address;
ajax.open('GET', url,true);
ajax.send();
}
}
document.getElementById("run").onclick = function(){
address = document.getElementById("address").value;
purpose = 1;
updateText(address);
}
</script>
</body>
</html>
ajaxQ.php - to see the difference, change "iperf -c" to "iperf3 -c" in the $iperfCmd variable.
<?php
function liveExecuteCommand($cmd,$address)
{
while (# ob_end_flush()); // end all output buffers if any
// tells the user what command is going to run
echo "<pre>Running Command: '".$cmd."'</pre>";
// open the command to run and read output
$proc = popen("$cmd", 'r');
$live_output = "";
$complete_output = "";
while (!feof($proc))
{
# flush();
$live_output = fread($proc,4096);
// adds the live output to the complete output
$complete_output = $complete_output . $live_output;
// prints the live output
echo "<pre>$live_output</pre>";
}
sleep(1);
// close the process
pclose($proc);
echo "<pre>------------------------------------------------------------\nAll Done!</pre>";
}
// this happens if the iPerf button is pressed
if (isset($_GET['address'])) {
$address = $_GET['address'];
$iperfCmd = "iperf -c ".$address." -i 1 -t 5";
liveExecuteCommand($iperfCmd,$address);
}
else{
echo "No post request";
}
?>
FYI, I am running the iperf client on an 'Ubuntu 16.04.2 LTS' CLI server and the iperf server on an 'Ubuntu 16.04 LTS' desktop server.
Thanks for any help!

Why C++ CGI form_iterator values not getting in XMLHttpRequest asynchronous Ajax request?

I wrote a sample HTML page with Ajax script . I have a .cgi file in cpp which will accept values from ajax and send message back to HTML page . Now i am facing the problem that i didn't get values in cgi script . This is my code :
HTML & ajax script :
<html>
<head>
<script type = "text/javascript">
var XMLHttp;
if(navigator.appName == "Microsoft Internet Explorer") {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
XMLHttp = new XMLHttpRequest();
}
function SentData () {
var name = document.getElementById('name').value ;
var postData;
XMLHttp.open("POST", "simplecgi.cgi", true);
postData = "";
postData += name;
XMLHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
XMLHttp.setRequestHeader("Content-length", postData.length);
XMLHttp.send(postData);
XMLHttp.onreadystatechange = function() {
document.getElementById('area').innerHTML = XMLHttp.responseText;
}
}
</script>
<h1>Simple application</h1>
<form id="newform">
Enter Name <input onkeyup = "javascript: SentData()" name ="name" id="name">
</form>
<div id = "area">
</div>
</body>
</html>
Here SentData function get textarea value and append with postdata and send it via XMLHttpRequest .
and the cpp cgi script :
include <unistd.h>
#include <iostream>
#include <vector>
#include <string>
#include "cgicc/Cgicc.h"
#include "cgicc/HTTPHTMLHeader.h"
#include "cgicc/HTMLClasses.h"
#include <stdio.h>
#include <string.h>
using namespace std;
using namespace cgicc;
int main(int argc, char **argv)
{
Cgicc cgi;
try {
// Send HTTP header
cout << HTTPHTMLHeader() << endl;
// Set up the HTML document
cout << html() << head(title("cgi sample")) << endl;
cout << body() << endl;
form_iterator name = cgi.getElement("name");
if( name != cgi.getElements().end()){
cout << "Content-Type: text/plain\n\n"<< **name << "sucess"<<endl;
cout << body() << html();
}
catch(exception& e) { }
return 0 ;
}
Here i want to get HTML text area value and then i am sending that value with sucess message back to HTML .
The problem i am facing now is i didn't get that form_iterator name = cgi.getElement("name");value . This is empty ? Why ?
But this is working fine when i use like
<form id="newform" action="simplecgi.cgi" method="POST">
Enter Name <input onkeyup = "javascript: SentData()" name ="name" id="name">
</form>
I don;t want to redirect my HTML page to .cgi page . For that i am using ajax . Why this error ? any suggestions ?
if I didn't use <form > like simply a text area with out form tag . Can i pass this textarea values to .cgi and get message back to HTML ?
application/x-www-form-urlencoded content, by definition, has to be encoded using this convention.
Your javascript code appears to blindly put a bare string value in the body of the POST. That's not the application/x-www-form-urlencoded format.
The format, roughly summarizing, is a list of "name=value" pairs, separated by ampersands, with each value %-encoded like in a URL, hence "urlencoded". Your javascript code sends just the value part, and fails to %-encode it altogether.
Fix your javascript so that the POST-ed content is correctly encoded. In general, it's going to be much easier to use any one of the freely available Javascript libraries to do all the work for you, like Jquery, instead of reinventing the wheel yourself.

How to parse XML soap response using Javascript

I'm using Javascript to call a SOAP webservice. Using firebug, I can see that the request is successful, and I see the XML SOAP response.
How can I display the response on the webpage? Or even better - how can I display a single node within the XML SOAP response? I thought maybe I can use XPath - but it doesn't seem to be working.
Here is my code:
<html>
<head>
<title>SOAP Client Test</title>
<script type="text/javascript">
function soap() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'https://mysoapurl.com', true);
// build SOAP request
var sr =
'<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">' +
'<s:Header> ' +
'<USERNAME xmlns="http://www.tempuri.org">MyUsername</USERNAME>' +
'<PASSWORD xmlns="http://www.tempuri.org">MyPassword</PASSWORD>' +
'</s:Header>' +
'<s:Body>' +
'<GetData>Foo</GetData>' +
'</s:Body>' +
'</s:Envelope>';
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.setRequestHeader('SOAPAction', 'http://tempuri.org/MySoapActionURL');
xmlhttp.send(sr);
// send request
// ...
// This XPath query should get us the <GetResponse> element from the SOAP XML Response
var query = "//ns1:GetResponse[1]";
// This object defines the namespaces used in the query
var namespaceMapping = {
ns1: "http://tempuri.org/", // SOAP namespace
diffgr: "urn:schemas-microsoft-com" // the service-specific namespace
};
// Extract the <GetResponse> element from the response document
var responseNode=XML.getNode(XMLHttpRequest.responseXML, query, namespaceMapping);
return responseNode;
}
window.onload = soap;
</script>
</head>
<body>
</body>
<html>
Any help is greatly appreciated. Thanks for looking.
You can use the evaluate method on the responseXML:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'https://mysoapurl.com', true);
// build SOAP request
var sr =
'<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">' +
'<s:Header> ' +
'<USERNAME xmlns="http://www.tempuri.org">MyUsername</USERNAME>' +
'<PASSWORD xmlns="http://www.tempuri.org">MyPassword</PASSWORD>' +
'</s:Header>' +
'<s:Body>' +
'<GetData>Foo</GetData>' +
'</s:Body>' +
'</s:Envelope>';
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.setRequestHeader('SOAPAction', 'http://tempuri.org/MySoapActionURL');
xmlhttp.onload = function(evt) {
var doc = this.responseXML;
var namespaceMapping = {
ns1: "http://tempuri.org/",
diffgr: "urn:schemas-microsoft-com"
};
var node = doc.evaluate('//ns1:GetResponse[1]', doc,
function (prefix) {
return namespaceMapping[prefix];
},
XPathResult.FIRST_ORDERED_NODE_TYPE,
null).singleNodeValue;
if (node != null) {
// now access node.textContent respectively run further queries on node
}
};
xmlhttp.send(sr);

Pass an argument from javascript to a python script

I have a python script from which I pass an argument to execute a query in an Oracle Database
prov.py
#!/usr/local/bin/python2.7
import sys
import argparse
import cx_Oracle
import json
import cgi
import cgitb
cgitb.enable()
lst_proveedores=[{}]
conn_str = 'user/pass#DATABASE'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
qstr = qstr = """ select id_proveedor, nombre, tipo from mpc_proveedores where tipo = '%s' """ %sys.argv[1]
c.execute(qstr)
for row in c:
record1 = {"id":row[0], "nombre":row[1],"tipo":row[2],"tipo":row[2]}
lst_proveedores.append(record1)
json_string = json.dumps(lst_proveedores)
print json_string
conn.close()
I need to show the data in an HTML page.
index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ajax_get_json(){
var results = document.getElementById("results");
var hr = new XMLHttpRequest();
hr.open("GET", "prov.py", true);
hr.responseType = "JSON";
hr.setRequestHeader("Content-Type", "application/json", true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
results.innerHTML = "";
for(var obj in data){
results.innerHTML +=
"<tr><td>"+data[obj].id+"</td><td>"+data[obj].nombre+"</td><td>" +data[obj].tipo+"</td></tr>";
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div class="container">
<div class+"row">
<table id="results" class="table table-bordered table-striped table-hover">
<tr>
<td>Id Proveedor</td>
<td>Nombre</td>
<td>Tipo</td>
</tr>
<script type="text/javascript">ajax_get_json();</script>
</table>
</div>
</div>
</body>
</html>
How can I execute the script from a button, and how can I pass a value from an input text to javascript?
Also, I know my javascript is not well designed. Any advice?
To run Python code from Apache you need to use a proper interface for it. There are many posibilities but CGI or mod_wsgi are popular alternatives. The Python docs has lots of useful info about how to set it up.
I think what you really want is a web framework.
That would provide a structured approach to exactly the type of stuff you're trying to do.
django is great and very popular. Pyramid and Flask are also very popular.
I have a good amount of experience with Flask and highly recommend it.

Categories

Resources