Python Forum

Full Version: getting options from a html form
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I have the following code in short, I want to use the <==> from op in my if statement.

[html]
<SELECT NAME=op>
<OPTION VALUE="<">Lesser then</option>
<OPTION VALUE="==">Equals to</option>
<OPTION SELECTED VALUE=">">Greater then</option>
</SELECT>
<input type=number name=seconds size=20>

op1=form.getvalue('op')   
if int(row[1]) op1 int(seconds)
   print(row[1],"something")
Hope you can help.
Cheers,
Patrick
Is this question about Django? If it is about Django, and form is assumed to be a valid Django form, you can access underlying data, e.g. as follows op = form.cleaned_data.get('form_field', 'fallback_value').

If you need to apply selected operation, you need to define a mapping, e.g.

allowed_operations = {
'==' : lambda x, y: x == y,
'>': lambda x, y: x > y
# etc.
# Also, you can look at 'operator' module.
}
def operation_not_found(*args):
    # You can raise exception here, print an error to stdout,eg.
    print("This operation isn't allowed")
    return False

op = '=='
op_func = allowed_operations.get(op, operation_not_found)

if op_func(x, y):
    pass 
    # do some stuff
I don't think this is what I mean, I want to use the operator from the form (<==>) (op1) in a if statement shown in line 2 from my example. There is no need to check if the value is allowed. I use a pulldown menu.
Ok, you can use eval built-in function, e.g.

if eval("int(row[1])" + op + "int(seconds)"):
    pass 
But eval is unsafe. What happens, if somebody set illegal
(or even malware) string to the op variable? Let op="; import os; os.system("arbitrary operating system command"); " or something else. So, injecting malware string to op will allow to execute arbitrary command (or code) on your computer.
Thanks, this works, great. And the programm is only used internally. It never touches internet.
Many thanks again.
Please don't use eval. Especially when there's totally fine options available. Like the operator module (https://docs.python.org/3/library/operator.html):
import operator

op_map = {
    ">": operator.lt,
    "==": operator.eq
}

op1 = form.getvalue('op')   
if op_map[op1](int(row[1]), int(seconds)):
   print(row[1], "something")