Created
December 18, 2010 17:51
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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