Error inserting data into MariaDB using the Python requests module - python

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.

Related

Pass multiple arguements from php to 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?

django: request.POST.get() returns NoneType

I am work from data acquired from an html form.
I am currently failing to capture the data on the server side. Every input returns "NoneType" on the server.
I feel like I tried everything that I could find around here, notably changing id for name in the html form, nothing works.
here is what I got so far:
views.py:
def quadriatransport_simulationView(request):
return render(request, "simulation.html")
#csrf_exempt
def compute(request):
destination = request.POST.get("destination")
nombre_de_palettes = request.POST.get("nombre_de_palettes")
poids_par_palette = request.POST.get("poids_par_palette")
Optimisation_prix = request.POST.get("Optimisation_prix")
Optimisation_delai = request.POST.get("Optimisation_delai")
result = {"destination":destination}
print(result)
return JsonResponse({"operation_result": result})
results returns a dictionnary where destination is None
now here is what I have been able to do on the webpage
<form method="POST">
{% csrf_token %}
<label><h3>Input variables to calculate EOQ:</h3></label>
<br>
<br>
<span>Destination (departement) <input type="text" id="destination">
<br>
<br>
<span>Nombre de palettes <input type="text" id="nombre_de_palettes">
<br>
<br>
<span>Poids par palette <input type="text" id="poids_par_palette">
<br>
<br>
<span>Optimiser prix <input type="checkbox" id="Optimisation_prix">
<br>
<br>
<span>Optimiser délai de livraion <input type="checkbox" id="Optimisation_delai">
<br>
<input id="ajax-call" type="submit" value="Simuler">
</form>
<p id="ajax"></p>
and here is my js script inside of the webpage
<script>
document.querySelector("#ajax-call").addEventListener("click", event => {
event.preventDefault();
let formData = new FormData();
formData.append('destination', document.querySelector("#destination").value);
formData.append('nombre_de_palettes', document.querySelector("#nombre_de_palettes").value);
formData.append('poids_par_palette', document.querySelector("#poids_par_palette").value);
formData.append('Optimisation_prix', document.querySelector("#Optimisation_prix").value);
formData.append('Optimisation_delai', document.querySelector("#Optimisation_delai").value);
let csrfTokenValue = document.querySelector('[name=csrfmiddlewaretoken]').value;
const request = new Request('{% url "compute" %}', {
method: 'POST',
body: formData,
headers: {'X-CSRFToken': csrfTokenValue}
});
fetch(request)
.then(response => response.json())
.then(result => {
const resultElement = document.querySelector("#ajax");
resultElement.innerHTML = result["operation_result"];
})
})
</script>
Not sure what is wrong with this, I have successfully used the same structure for other projects and it worked. I have been struggling with it for hours that I can't see straight. Hopefully someone can see where I messed up!
You misspelled destination in your formData
formData.append('destination', document.querySelector("#destination").value);

Inserting into mysql table with flask [duplicate]

This question already has an answer here:
Number of MySQL query parameters match arguments passed to execute, but Python raises "not all arguments converted"
(1 answer)
Closed 5 years ago.
Hi I am having difficulties inserting values into my database.
I am able to log in using the same method I use for the sign up page.
I have tried a lot of different options but nothing seemed to work.
Here is my python code:
from flask import Flask, request, render_template, url_for
import pymysql.cursors
app = Flask(__name__)
# Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='1234',
db='mydb',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
#app.route('/')
def index():
return render_template('signup.html')
#app.route('/signup', methods=['POST', 'GET' ])
def signup():
cursor = connection.cursor()
if request.method == 'POST':
try:
cursor.execute('''INSERT INTO users (user, fname, lname, email, pnum, password) VALUES (%s, %s, %s, %s, %s, %s)''')
cursor.commit()
finally:
return render_template('login.html')
if __name__ == '__main__':
app.run(debug=True)
and my HTML:
<h1>Please Sign Up</h1>
<button onclick="document.getElementById('id01').style.display='block'"style="width:auto;">Sign Up</button>
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<form class="modal-content animate" action="/signup" method="POST">
<div class="container">
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<label><b>user</b></label>
<input type="text" placeholder="user" name="user" required>
<label><b>First name</b></label>
<input type="text" placeholder="First name" name="fname" required>
<label><b>pnum</b></label>
<input type="text" placeholder="Pnum" name="pnum" required>
<label><b>Last name</b></label>
<input type="text" placeholder="Last name" name="lname" required>
<input type="checkbox" checked="checked"> Remember me
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" action="/Signup" method="POST" class="signupbtn">Sign Up</button>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
You could do something like:
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('abc#python.org', 'very-secret'))
Pay special attention to " " and back-ticks `` in the query. Your query seems to be faulty. There are no values for the placeholders %s.
Hope that helps.

Log into website in Python script

I'm trying to log into a website and then perform some tasks to retrieve some data I need. I've been looking at examples of ways to login but nothing I've tried seems to work for my case. I've heard that the "requests" module is something that I should utilize.
Here is the form section of the login page (https://verification.nws.noaa.gov/services/public/login.aspx):
<form name="PageForm" method="POST" action="/services/public/login.aspx" id="PageForm">
.
.
(a little ways down)
.
.
<p>
<label for="Username">Username:</label>
<br>
<input name="UsernameBox" type="text" id="UsernameBox">
</p>
<p>
<label for="Password">Password:</label>
<br>
</p>
<p>
<input type="submit" name="LoginBtn" value="Login" onclick="javascript: WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("LoginBtn", "", true, "", "", false, false))" language="javascript" id="LoginBtn" class="btn">
</p>
.
.
</form>
This is what I have for my Python code so far and it doesn't seem to login or work:
import requests
# Log into the NWS Performance Management site to get Storm Data.
url = 'https://verification.nws.noaa.gov/services/public/login.aspx?'
values = {'UsernameBox': 'myuser',
'PasswordBox': 'mypass',
'LoginBtn': 'Login'}
session = requests.session()
r = session.post(url, data=values)
# Try opening private webpage when logged in.
r = session.get('https://verification.nws.noaa.gov/stormdat/downloads/csv/index.aspx#top')
Any help would be greatly appreciated. Thanks!
You just missed a few fields in your payload, you can get them from the login page.
<body><form name="PageForm" method="POST" action="/services/public/login.aspx" id="PageForm">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUIMzc4Mzk0MzlkZF/afEu7JIuhzEtWu2QqdxDm88Un" />
So, your values should like like this
values = {
'__EVENTTARGET': '',
'__EVENTARGUMENT': '',
'__VIEWSTATE' 'Get this value from the login page',
'__VIEWSTATEGENERATOR' 'Get this value from the login page',
'UsernameBox' 'myuser',
'PasswordBox' 'mypass',
'LoginBtn' 'Login'
}

OS Error : Error No 22

This is the error :
127.0.0.1 - - [22/Jun/2015 17:15:21] "POST /cgi-bin/get_tran_data.py HTTP/1.1" 2
00 -
127.0.0.1 - - [22/Jun/2015 17:15:21] command: C:\Python34\python.exe -u C:\Pytho
n34\ProjectShivam\webapp\cgi-bin\get_tran_data.py ""
127.0.0.1 - - [22/Jun/2015 17:15:22] b'Traceback (most recent call last):\r\n F
ile "C:\\Python34\\ProjectShivam\\webapp\\cgi-bin\\get_tran_data.py", line 20, i
n <module>\r\n with open("C:\\Python34\\ProjectShivam\\webapp\\cgi-bin\\tran_
add_success.py") as g:\r\nOSError: [Errno 22] Invalid argument: \'C:\\\\Python34
\\\\ProjectShivam\\\\webapp\\\\cgi-bin\\tran_add_success.py\'\r\n'
127.0.0.1 - - [22/Jun/2015 17:15:22] CGI script exit status 0x1
get_tran_data.py:
import cgi
import yate
import sqlite3
import sys
connection = sqlite3.connect('users.sqlite')
cursor = connection.cursor()
print('Content-type:text/html')
form=cgi.FieldStorage()
doctype=form['doctype'].value
docno=form['docno'].value
docdate=form['docdate'].value
bincard=form['bincard'].value
rate=form['rate'].value
quantity=form['qty'].value
cursor.execute("INSERT INTO TRAN(DOCTYPE,DOCNO,DOCDATE,BINCARD,QTY,RATE) VALUES (?,?,?,?,?,?)",(doctype,docno,docdate,bincard,rate,quantity))
connection.commit()
with open("C:\Python34\ProjectShivam\webapp\cgi-bin\tran_add_success.py") as g:
code = compile(g.read(),"tran_add_success.py", 'exec')
exec(code)
When i remove the open statement from get_tran_data.py, the script runs successfully. I used a similar open statement in another script and that ran successfully but here i don't know what is the problem?
EDIT:
This is get_opb_data.py, the script with similar code but runs successfully:
import cgi
import yate
import sqlite3
import sys
connection = sqlite3.connect('users.sqlite')
cursor = connection.cursor()
print('Content-type:text/html')
form=cgi.FieldStorage()
bincard=form['bincard'].value
desc=form['desc'].value
loc=form['loc'].value
qty=form['qty'].value
rate=form['rate'].value
Value=form['value'].value
currate=form['currate'].value
curqty=form['curqty'].value
cursor.execute("INSERT INTO OPB(Bincard,Description,Location,Quantity,Rate,Value,CurRate,CurQty) VALUES (?,?,?,?,?,?,?,?)",(bincard,desc,loc,qty,rate,Value,currate,curqty))
connection.commit()
with open("C:\Python34\ProjectShivam\webapp\cgi-bin\opb_add_success.py") as f:
code = compile(f.read(), "opb_add_success.py", 'exec')
exec(code)
Also, the tran_add_success.py file exists, I have made sure of that. I don't get why this is happening, that once script is running just fine and the other isnt.
tran.html:
<html>
<head>
<title>Transaction</title>
<link type="text/css" rel="stylesheet" href="coach.css" />
</head>
<body>
<img src="images/logo-cel-transparent_0.png" width="74" height="64"><strong><img src="images/logo-cel-transparent_0.png" alt="Cel logo" width="74" height="64" align="right">
</strong>
<h1 align="center"><strong>Central Electronics Limited</strong></h1>
<p> </p>
<h2 align="center">Storage Management System</h2>
<p> </p>
<div align="center"><strong>Transaction!!</strong></div>
<p align="left"> </p>
<p align="center">
<form action="cgi-bin/get_tran_data.py" method="post">
<div align="center">DocType :
<input type="text" name="doctype">
DocNo :
<input type="text" name="docno">
DocDate :
<input type="text" name="docdate">
<br><br>
BinCard :
<input type="text" name="bincard">
Rate :
<input type="text" name="rate">
Quantity :
<input type="text" name="qty">
<br>
<p align="center"><input type="submit" value="Submit"></p>
</div>
</form>
</p>
</body>
</html>
When i click the submit button on tran.html, the get_tran_data.py runs. Now it fetches the data from the form and saves it to database. I use open statement in get_tran_data.py so as to run another script which displays a success message on the screen.

Categories