Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML form POST to a python script?

Tags:

python

html

Does anyone know of any good resources for information on how to POST data from a HTML form over to a python script?

like image 771
Skizit Avatar asked Oct 05 '10 10:10

Skizit


People also ask

How do I pass data from HTML form to Python?

You can pass information by simply concatenating key and value pairs along with any URL or you can use HTML <FORM> tags to pass information using GET method.

How do I display HTML output in Python?

In order to display the HTML file as a python output, we will be using the codecs library. This library is used to open files which have a certain encoding. It takes a parameter encoding which makes it different from the built-in open() function.


1 Answers

For a very basic CGI script, you can use the cgi module. Check out the following article from the Python documentation for a very basic example on how to handle an HTML form submitted through POST:

  • Web Programming in Python : CGI Scripts

Example from the above article:

#!/usr/bin/env python

import cgi
import cgitb; cgitb.enable()  # for troubleshooting

print "Content-type: text/html"
print

print """
<html>

<head><title>Sample CGI Script</title></head>

<body>

  <h3> Sample CGI Script </h3>
"""

form = cgi.FieldStorage()
message = form.getvalue("message", "(no message)")

print """

  <p>Previous message: %s</p>

  <p>form

  <form method="post" action="index.cgi">
    <p>message: <input type="text" name="message"/></p>
  </form>

</body>

</html>
""" % message
like image 143
Daniel Vassallo Avatar answered Oct 12 '22 23:10

Daniel Vassallo