HTML 表单 POST 到 python 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3862788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:06:26  来源:igfitidea点击:

HTML form POST to a python script?

pythonhtml

提问by Skizit

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

有谁知道有关如何将数据从 HTML 表单发布到 python 脚本的信息的任何好的资源?

回答by Daniel Vassallo

For a very basic CGIscript, 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:

对于非常基本的CGI脚本,您可以使用cgi 模块。查看 Python 文档中的以下文章,了解如何处理通过 提交的 HTML 表单的基本示例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

回答by jonesy

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。如果您只是想模拟向 Web 服务器发布表单的用户,您可以执行以下操作:

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.

还有很多其他选择。IIRC,'-F' 使用 'multipart/form-data' 并且用 '--data' 替换 -F 将使用 urlencoded 表单数据。非常适合快速测试。

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

如果您必须为此使用 Python 而不是命令行,我强烈推荐“海报”模块。http://atlee.ca/software/poster/——它让这一切变得非常非常简单(我知道,因为我没有这个模块就完成了,这很头疼)。