HTML form POST to a python script?

后端 未结 2 1441
醉酒成梦
醉酒成梦 2020-12-28 09:28

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

相关标签:
2条回答
  • 2020-12-28 09:56

    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).

    0 讨论(0)
  • 2020-12-28 10:09

    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
    
    0 讨论(0)
提交回复
热议问题