2

I have got the following HTML form with several complicated input elements:

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

When I talk about cimplicated inputs I mean sophisticated name of elements:

name="images[1]"

Where images is indicate group of input and [1] number or identificator of input.

Using PHP approach of handling form It can be achieved like:

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

How to reproduce this in Python?

Jessie
  • 373
  • 2
  • 6
  • 17

2 Answers2

2

it depends if you are using a python framework (django, Flask, ...) or not. if you are using a framework, you must read its docs. for example with django, you can handle form element by request.POST['images'].

you can read How are POST and GET variables handled in Python?

layekams
  • 49
  • 6
  • I use Flask framework – Jessie Dec 09 '17 at 12:58
  • it's cool then. it's same as Django. – layekams Dec 09 '17 at 19:02
  • you just need to import request. and then request.post['images']. hope it can help you... Tell me if it not work – layekams Dec 09 '17 at 19:04
  • 1
    You can also find another way to do it if you read Flask documentation: http://flask.pocoo.org/docs/0.12/quickstart/. for example : @app.route('/route_dest', methods=['POST']) def handle_method(): images_list = request.form['images'] – layekams Dec 09 '17 at 19:14
0

It is easy with HTMLParser.

Take a look at this example.

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]">')

Than you have

python a1.py
Start tag: input
     attr: ('type', 'text')
     attr: ('name', 'images[1]')
Richard Rublev
  • 7,718
  • 16
  • 77
  • 121