Pass multiple arguements from php to python? - python

<html>
<body>
<head>
<title>HTML Forms</title>
</head>
<p>Add your details:</p>
<form name="form" method="get">
Number 1:<br> <input type="number" name="first">
<br>
Number 2:<br> <input type="number" name="second">
<br>
Number 3:<br> <input type="number" name="third">
<input type="submit" value="submit" id="submit" />
</form>
</body>
</html>
<?php
$var1 = $_GET['first'];
$var2 = $_GET['second'];
$var3 = $_GET['third'];
$command = escapeshellcmd("python total.py $var1 $var2 $var3");
$output = shell_exec($command);
echo ($output);
?>
import sys
num_1 = sys.argv[1]
num_2 = sys.argv[2]
num_3 = sys.argv[3]
print("total:", num_1+num_2+num_3)
I have shared the code I am using. I want to get the values from user using the HTML code and read it using PHP. Then pass the values from PHP script to python script, do the task and display the output.
For some reason I am unable to do that. Can someone help me?

Related

Error inserting data into MariaDB using the Python requests module

I am trying to create a Python script that will fill some information in the database. For the server side I have used PHP and when I try to submit information using a browser, it works. But when I try to do it using the below Python script, it doesn't.
import requests
url_insert = 'http://192.168.1.100/data.php'
data_insert = {'fullname':'spiderman',
'ssn':'1234',
'dept':'Security',
'salary':10000,
'homeaddress':'New York',
'btn_save':'Save'}
req = requests.post(url_insert, data = data_insert)
print(req.text)
I get the following error:
INSERT INTO emp_record (ename, ssn, dept, salary, homeaddress) VALUES ('', '', '', , '')<br>You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' '')'
The code for data.php is:
<?php
require("database.php");
if (isset($_POST["btn_save"])) {
$fullname = $_POST["fullname"];
$ssn = $_POST["ssn"];
$dept = $_POST["dept"];
$salary = $_POST["salary"];
$homeaddress = $_POST["homeaddress"];
echo $fullname . "<br>";
echo $ssn . "<br>";
echo $dept . "<br>";
echo $salary . "<br>";
echo $homeaddress . "<br>";
}
$sql = "INSERT INTO emp_record (ename, ssn, dept, salary, homeaddress)
VALUES ('$fullname', '$ssn', '$dept', $salary, '$homeaddress')";
$result = mysqli_query($conn, $sql);
if ($result) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
This shows the contents of the database connection file:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "employees";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "Connected Successfully." . "<br>";
}
And the following is the contents of the index.php file which contains the HTML form:
<html>
<head>
<title>RETRIEVE DATA</title>
</head>
<body>
<form action="data.php" method="POST">
<div class="form-group">
<label for="id">Full Name</label>
<input type="text" name="fullname" id="fullname" value="" placeholder="FullName">
<br>
<br>
<label for="id">Social Security Number</label>
<input type="text" name="ssn" id="ssn" value="" placeholder="Social Security Number">
<br>
<br>
<label for="id">Department</label>
<input type="text" name="dept" id="dept" value="" placeholder="Department">
<br>
<br>
<label for="id">Salary</label>
<input type="text" name="salary" id="salary" value="" placeholder="Salary">
<br>
<br>
<label for="id">Address</label>
<input type="text" name="homeaddress" id="homeaddress" value="" placeholder="Address">
<br>
<br>
<input type="submit" name="btn_save" value="Save">
</div>
</form>
</body>
</html>
I don't know why it is giving me database related error. Because when I try to enter data using a browser, it gets saved inside the database table.

in CGI, how it is possible to use both python code and html code

How can I use both HTML and Python code in same file in CGI as we can do the same thing wiht PHP and HTML.
I have following HTML code in Python file.
#!C:/python36/python.exe
import cgi
print("Content-type:text/html")
print("""
<html>
<head><title>html form</title></head>
<body style='background-color:red;'>
<form method="POST" action="#">
<input type="text" placeholder="username" name="username">
<input type="text" placeholder="password" name="password">
<input type="submit" value="submit" name="send">
</html>""")
now I want use python code in this file to get form data and my python code is as follow:
form = cgi.FieldStorage()
username = form.getvalue("username")
password = form.getvalue("password")
print(username,password)
Now, if submit is clicked, I want Python code to be executed and also I do not want to reference my Python code in form action.

Pass Python parameters to HTML

I've the following HTML code:
<html>
<form action="index.php" method="post">
Enter Input:
<input type="text" class="textbox" name="usn" id="usn" required />
<input class="buttongo" type="submit" value="Go" />
<input type="hidden" name="task" value="getResult"/>
</form>
</html>
I want to write a python script, which executes the above HTML, passing a value parameter to the first input statement to the above HTML. That is,
<html>
<form action="index.php" method="post">
Enter Input:
<input type="text" class="textbox" name="usn" id="usn" value="FromPython" />
<input class="buttongo" type="submit" value="Go" />
<input type="hidden" name="task" value="getResult"/>
</form>
</html>
Further, is there a way in which I can directly send the value to index.php and get the response?
(P.S.: I want to loop the value from 0 to 100 and save the response generated in a file)
Why don't you send the request using python ? You can send the requests inside a loop and pass the parameters you want.
Making requests with the requests module
sample code :
import requests
for i in range(101):
payload = {'usn': i}
response = requests.post("index.php", data=payload)
# do something with response
Use urllib module, documentation at: https://docs.python.org/2/library/urllib.html
As described in the link, this module provides a high-level interface for fetching data across the World Wide Web.

Pass string from html to python script

I need help, I have a Python script that do some work and print html web page.
I need to pass string from that outputed web page to that script.
Is that possible ?
In future I want to use radio buttons where user will thick data for plotting from predefinned ones.
Thanks for any advice...
My code:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# enable debugging
import cgitb
cgitb.enable()
import subprocess
import os
print "Content-type: text/html\n\n";
web = """
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
</head>
<body>
<div id='wrapper'>
<div id='header'>
</div>
<div id='content'>
<div class='content'>
<div><h3>GRAPH</h3></div>
<br>
<div style='height:520px;width:1000px;overflow:scroll;overflow-x:auto;overflow-y:hidden;'>
<img src='http://localhost/steps.png' alt='image' />
</div>
<br>
<button onclick="myFunction()">REFRESH</button>
<script>
function myFunction() {
location.reload();
}
</script>
<br>
<form action='/cgi-bin/test.py' method='post'>
nazov suboru: <input type='text' data='data'> <br />
<input type='submit' value='Submit' />
</form>
</div>
</div>
</div>
</body>
</html>
"""
print web
proc = subprocess.Popen(['gnuplot','-p'],
shell=True,
stdin=subprocess.PIPE,
)
proc.communicate("""
reset
set terminal pngcairo enhanced size 3000,500 font 'Arial,11' rounded;
set output '/opt/lampp/htdocs/%s.png'
set datafile separator "|"
plot \
\
'%s.txt' u 0:3 sm cs w l ls 1 t 'X-suradnice',\
'%s.txt' u 0:4 sm cs w l ls 2 t 'Y-suradnice',\
'%s.txt' u 0:5 sm cs w l ls 3 t 'Z-suradnice'
"""%(data,data,data,data))
Your question is quite hard to understand, but I think you are trying to work out how to access the data parameter submitted by the form POST. You can do that with the cgi module:
import cgi
form = cgi.FieldStorage()
data = form.getvalue('data')

Pyramid - uploading images and storing on disk

I'm trying to implement a system of uploading a file (image) to the server running pyramid. Right now, this code gives me an AttributeError: 'unicode' object has no attribute 'file' exception:
Server-side:
session = Session()
username = authenticated_userid(request)
if username == None:
return HTTPNotFound()
else:
user = session.query(User).filter(User.username == username).first()
if 'photo.submitted' in request.params:
input_file = request.POST['file_input'].file
tmp = '../static/images/%s' % (session.query(ProfilePic).order_by(-ProfilePic.photo_id).first().photo_id + 1)
open(tmp, 'w').write(input_file.read())
tmp.close()
return Response('OK')
return {}
HTML:
<html>
<body>
<form action="/settings" method="post">
<input type="file" name="file_input" value="Choose image" />
<p><input type="submit" name="photo.submitted" value="Save" /></p>
</form>
</body>
</html>
Something that seems simple, but won't work. I was trying to follow this tutorial, but it seems it only works with video/audio files. How could I make this work?
For file uploads, you need to alter the form enctype to use multipart/form-data:
<html>
<body>
<form action="/settings" method="post" enctype="multipart/form-data">
<input type="file" name="file_input" value="Choose image" />
<p><input type="submit" name="photo.submitted" value="Save" /></p>
</form>
</body>
</html>

Categories