hretic hretic - 1 year ago 72
Python Question

Converting GET request parameter to int ... if it is numeric

lets say i'm showing some data to user , i want user to be able to perform some sort of filtering on a numeric field in the database using a

form so i have something like this

code = request.GET.get('code')
condition = {}
if( code is not None and int(code) > 0 ):
condition['code'] = int(code)


but this works only if i code contains a number otherwise i get this error

invalid literal for int() with base 10: ''

so what is the pythonic way to handle this problem ? should i use
block? i perfer to handle this in the same
statement considering i might add other filters

Answer Source

isnumeric could check if code can be casted to int and also check that code is positive (when converted to integer) thus replacing int(code) > 0:

if code is not None and code.isnumeric():
    condition['code'] = int(code)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download