Web2py comparing part of a request.vars element

2019-09-18 16:42发布

问题:

I have a form with a table with rows containing SELECTs with _names with IDs attached, like this:

TD_list.append(TD(SELECT(lesson_reg_list, _name='lesson_reg_' + str(student[4]))))

When the form is submitted I want to extract both the student[4] value and the value held by request.vars.lesson_reg_student[4].

I've tried something like:

for item in request.vars:
    if item[0:9] == "lesson_reg":
        enrolment_id = int(item[10:])
        code = request.vars.item

I also tried treating request.vars like a dictionary by using:

for key, value in request.vars:
    if key[0:9] == "lesson_reg":
        enrolment_id = int(key[10:])
        code = value

but then I got 'too many values to unpack'. How do I retrieve the value of a request.vars item when the last part of its name could be any number, plus a substring of the item name itself?

Thanks in advance for helping me.

回答1:

In Python, when slicing, the ending index is excluded, so your two slices should be 0:10 and 0:11. To simplify, you can also use .startswith for the first one:

for item in request.vars:
    if item.startswith('lesson_reg'):
        enrolment_id = int(item[11:])
        code = request.vars.item