Skip to content

Instantly share code, notes, and snippets.

@changtimwu
Created December 18, 2010 17:51
Show Gist options
  • Select an option

  • Save changtimwu/746706 to your computer and use it in GitHub Desktop.

Select an option

Save changtimwu/746706 to your computer and use it in GitHub Desktop.
a decorator for bottle which checks http query parameters with the applied function's argument spec
import json
from bottle import route, run, request
def params_check():
def decorator(func):
argnames=func.func_code.co_varnames[:func.func_code.co_argcount]
defnames = argnames[ (len(argnames)-len( func.func_defaults )):]
def wrapper(*args, **kwargs):
for argname in argnames:
if argname in request.GET:
kwargs[argname]=request.GET[argname]
else:
if argname not in defnames:
return json.dumps( {'ERROR': 'You must specify {0}'.format(argname) })
return func(*args, **kwargs)
return wrapper
return decorator
@route('/argtest')
@params_check()
def argtest( no, pos=0):
return 'no={0}, pos={1}'.format( no, pos)
run(host='localhost', port=8080)
#simple test commands
#curl "http://localhost:8080/argtest"
#curl "http://localhost:8080/argtest&no=33"
#curl "http://localhost:8080/argtest&no=33&pos=3"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment