【问题标题】:How to handle complicated input form in Python according PHP approach? [duplicate]如何根据 PHP 方法处理 Python 中复杂的输入表单? [复制]
【发布时间】:2017-12-09 12:15:11
【问题描述】:

我得到了以下带有几个复杂输入元素的 HTML 表单:

<input type="text" name="images[1]">
<input type="text" name="images[2]">
<input type="text" name="video[1]">
<input type="text" name="video[2]">

当我谈论 cimplicated 输入时,我指的是复杂的元素名称:

name="images[1]"

其中images 表示输入组,[1] 表示输入的编号或标识符。

使用PHP方式处理表单可以这样实现:

if(isset($_POST['images'])) {
    foreach($_POST['images'] as $index) { // $key
         echo $_POST['images'][$index]; // or key
    }
}

如何在 Python 中重现这个?

【问题讨论】:

  • 这是类似的问题,但有点不同,因为括号内有键

标签: php python python-2.7


【解决方案1】:

这取决于您是否使用 python 框架(django、Flask、...)。 如果您使用的是框架,则必须阅读其文档。例如使用 django,您可以通过 request.POST['images'] 处理表单元素。

你可以阅读How are POST and GET variables handled in Python?

【讨论】:

  • 我使用 Flask 框架
  • 那很酷。和 Django 一样。
  • 你只需要导入请求。然后 request.post['images']。希望它可以帮助你...告诉我如果它不起作用
  • 如果您阅读 Flask 文档,还可以找到另一种方法:flask.pocoo.org/docs/0.12/quickstart。例如:@app.route('/route_dest', methods=['POST']) def handle_method(): images_list = request.form['images']
【解决方案2】:

使用 HTMLParser 很容易。

看看这个例子。

from HTMLParser import HTMLParser
from htmlentitydefs import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print "Start tag:", tag
        for attr in attrs:
            print "     attr:", attr

    def handle_endtag(self, tag):
        print "End tag  :", tag

    def handle_data(self, data):
        print "Data     :", data

    def handle_comment(self, data):
        print "Comment  :", data

    def handle_entityref(self, name):
        c = unichr(name2codepoint[name])
        print "Named ent:", c

    def handle_decl(self, data):
        print "Decl     :", data

parser = MyHTMLParser()

parser.feed('<input type="text" name="images[1]">')

比你有的

python a1.py
Start tag: input
     attr: ('type', 'text')
     attr: ('name', 'images[1]')

【讨论】:

  • 据我所知,OP 询问的是如何处理已发布的表单/数据,而不是如何解析 HTML。
  • @MagnusEriksson 你说得对,我没注意。
  • 我使用 Flask 框架
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-02
相关资源
最近更新 更多