I see -- you're right.
The request.args structure is a List() object which web2py defines to
retrieve values without the exception if it doesn't exist. It has some
additional interesting capabilities... You can define a default value,
such as this:
request.args(0,default='Both')
This will substitute the value 'Both' for request.args[0] should it be set
to None or be invalid. Or you could cast a string value to an integer --
this often happens since the request.args are strings by default, but I
often pass row ids to be processed elsewhere:
URL('default','editrecord',args=[22])
Becomes:
http://...../default/editrecord/22
And request.args[0] is now '22' (the string). So we use the "cast" keyword
to change it to an int:
request.args(0,cast=int)
There is a ton of behavior in this little class! Thanks for pointing it
out to me.
-- Joe Barnhart
class List(list):
"""
Like a regular python list but a[i] if i is out of bounds return None
instead of IndexOutOfBounds
"""
def __call__(self, i, default=None, cast=None, otherwise=None):
"""
request.args(0,default=0,cast=int,otherwise='http://error_url')
request.args(0,default=0,cast=int,otherwise=lambda:...)
"""
n = len(self)
if 0 <= i < n or -n <= i < 0:
value = self[i]
else:
value = default
if cast:
try:
value = cast(value)
except (ValueError, TypeError):
from http import HTTP, redirect
if otherwise is None:
raise HTTP(404)
elif isinstance(otherwise, str):
redirect(otherwise)
elif callable(otherwise):
return otherwise()
else:
raise RuntimeError("invalid otherwise")
return value
On Tuesday, November 6, 2012 2:24:53 PM UTC-8, Niphlod wrote:
>
>
> One more point -- your "request.args(1)" should be "request.args[1]"
>> (with square brackets). The first form calls request.args as a function
>> and passes it the value "1". The second form treats request.args as a
>> Storage object and asks for the subscript "1".
>>
>> -- Joe Barnhart
>>
>> Nope, request.args(1) does basically
> try:
> result = request.args[1]
> except:
> result = None
> return result
>
> the () notation is safer because using request.args[1] if there is no
> request.args[1] you get an exception.
>
--