pythongoogle-app-enginejinja2tipfy

Accessing unknown query arguments in Python


I'm using Jinja2 to generate a form with a variable number of inputs, labelled input_1, input_2, etc. Using Google App Engine (python), I'm then trying to access the values of these inputs in my request handler using self.request.args.get().

However, depending on the number of inputs generated by the form, the script needs to read multiple variables. The script knows how many there will be, so the question is just how to use some kind of variable variable in a for loop to read them all efficiently.

The kind of thing I'm after is conceptually like this:

for x in total_inputs:
  list.append(input_x)

I could of course just use if statements for different numbers of inputs and do the variable names manually, but that seems awfully clunky - surely there is a better way?

Many thanks


Solution

  • You can do this with string formatting, like so:

    num = 5
    tag = 'input_%d' % num
    

    So to assemble a list of the values of all the input_x tags, you could do something like this:

    input_values = []
    for i in range(1, number_of_values + 1):
      input_values.append(self.request.get('input_%d' % i))
    

    This assumes you know how many values to retrieve. Your question presupposes you do, but in the case that you didn't, you can iterate over the results until you get an empty string (the default return value from request.get for a nonexistent label).

    Edit: The above comment assumed you're using webapp. Other frameworks may throw a KeyError if you try and call get for an argument that doesn't exist, and with no default specified.