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.
-
Are you trying to render the HTML using python? And then put information into your html page that python can consume?C.Nivs– C.Nivs2020年04月12日 03:22:48 +00:00Commented Apr 12, 2020 at 3:22
-
No. The HTML will POST the data TO the Python script.James– James2020年04月12日 03:46:03 +00:00Commented Apr 12, 2020 at 3:46
-
I think the python process needs to be reading from a socket/web-address for that to occur. The HTML is doing an http post to an arbitrary address (best I can tell). You'd need python to be running a basic HTTP server and the url of that server is what your html posts toC.Nivs– C.Nivs2020年04月12日 03:51:19 +00:00Commented Apr 12, 2020 at 3:51
-
You are in need of some sort of backend to make this work, Flask is a framework that enables this, and there are many others (django, bottle, etc). If you're looking for a built in, simple one, the http module can be of helpC.Nivs– C.Nivs2020年04月12日 03:59:37 +00:00Commented Apr 12, 2020 at 3:59
-
1I have Apache2.4 configured for my PHP app and added the CGI for python and now can run Python scripts from the web browser. Just missing a way to send information to the script.James– James2020年04月12日 04:11:38 +00:00Commented Apr 12, 2020 at 4:11
1 Answer 1
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.