Reputation: 221
I want to post data to a python script using a basic html form. My background is PHP and that's super easy with the $_POST superglobal. However, after hours of googling and YouTube, I'm still no closer. I've tried the Requests library but I want to RECEIVE information, not send it. I know I can probally use Flask but I would rather not have a framework. Is there a python equivalent to a superglobal?
Basically, I have an html form like,
<form method="post" name="MyFrom" action="data.php">
<input name="Data" type="text">
<input name="Submit1" type="submit" value="submit">
</form>
The data.php looks like,
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
?>
Which prints out... Array ( [Data] => 123 [Submit1] => submit ) ... and the "Data" value I can then assign to a variable and use latter down the script. Basically, I want a Python file (like data.py) that can understand the incoming post data.
Upvotes: 2
Views: 2927
Reputation: 714
While frameworks that run on WSGI, such as Flask, are much more suitable for building complex applications, a simple Python CGI script comes close to the way that PHP works.
form.html
<form method="post" name="MyFrom" action="/cgi-bin/data.py">
<input name="Data" type="text">
<input name="Submit1" type="submit" value="submit">
</form>
cgi-bin/data.py (don't forget to mark as executable)
#!/usr/bin/env python3
import cgi
print("Content-type:text/html\r\n\r\n")
print('<pre>')
form = cgi.FieldStorage()
for var in form:
print("field:", var)
print("value:", form[var].value)
print('</pre>')
You can test it using python3 -m http.server --cgi 8000
or install a full webserver like Apache with the CGI module.
Upvotes: 1