14

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

1

2 Answers 2

9

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:

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
Sign up to request clarification or add additional context in comments.

2 Comments

I'm coming from a HTML / JS / php background and sort of confusing myself. What format is the above example? How would I point a browser to it?
@Meowmix: It's exactly like php, but using python. It is executed by your web server, and renders the HTML page with a simple form. When the form is posted back to the script, it simply renders back the posted message.
0

You can also just use curl on the command line. If you're just wanting to emulate a user posting a form to the web server, you'd do something like:

curl -F "user=1" -F "fname=Larry" -F "lname=Luser" http://localhost:8080

There are tons of other options as well. IIRC, '-F' uses 'multipart/form-data' and replacing -F with '--data' would use urlencoded form data. Great for a quick test.

If you need to post files you can use

curl -F"@mypic.jpg" http://localhost:8080 

And if you have to use Python for this and not a command line, I highly recommend the 'poster' module. http://atlee.ca/software/poster/ -- it makes this really, really easy (I know, 'cos I've done it without this module, and it's a headache).

2 Comments

While using curl is a quick way from the console, the OP asked for a python solution. It may be good to focus on the main point (from HTML to python) with some examples, and perhaps, later, add the curl alternative from the console
@David - the OP actually did not ask for a python solution - they asked how to post data to an arbitrary Python script - not how to process posted data using Python. I'm happy to call it a misunderstanding on my part of the OPs question. However, for future reference, it may be good not to imply that other posters who are trying to help are somehow incapable or unwilling to "focus on the main point".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.