from flask import Flask, request
app = Flask(__name__)
class DotDict(object):
def __init__(self, inner):
self._inner = inner
def __getattr__(self, item):
return self._inner.get(item)
def get(self, item, default=None):
return self._inner.get(item, default)
class LazyAttribute(object):
def __init__(self, obj, attr):
self.obj = obj
self.attr = attr
def __getattribute__(self, item):
return getattr(getattr(object.__getattribute__(self, 'obj'),
object.__getattribute__(self, 'attr')),
item)
rargs = DotDict(LazyAttribute(request, 'args'))
@app.route("/")
def hello():
print rargs.a, rargs.c, rargs.get('d', 3)
return "Hello World!"
if __name__ == "__main__":
app.run(debug=True)
Accessing http://localhost:5000/?a=1 prints 1 None 3 in the terminal.
The LazyAttribute class is because calling just DotDict(request.args) outside of a request context throws an error. The alternative is to make a function:
def rargs():
return DotDict(request.args)
but I wanted to make usage as smooth as possible.
request.args.getto somegetargvariable to get rid of the redundancy, but other than that this seems optimal. If you want something fancier and have many endpoints and plenty of time, you might write a decorator that maps request args to the view function arguments.