Pythonic方式访问Flask请求争论

时间:2016-05-31 07:54:02

标签: python flask

在我的Flask应用程序中,我使用

设置了一些通过API调用进入的局部变量
from flask import request
.
.
submission_id = request.args.get('submission_id')
grader = request.args.get('grader')
grading_factor = float(request.args.get('grading_factor'))
answer_key = request.args.get('answer_key')
submission_key = request.args.get('submission_key')

设置这5个变量的重复性较低或更多的Pythonic方式是什么?

3 个答案:

答案 0 :(得分:2)

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)

在终端中访问http://localhost:5000/?a=1打印1 None 3

LazyAttribute类是因为在请求上下文之外调用DotDict(request.args)会引发错误。另一种方法是建立一个功能:

def rargs():
    return DotDict(request.args)

但我希望尽可能顺利使用。

答案 1 :(得分:2)

正如我在评论中建议的那样,你可以想出一个装饰器,它将请求参数映射到相应的函数参数,例如:

def map_args(func):
    @functools.wraps(func)
    def wrapper(**kwargs):
        all_args = dict(request.args, **kwargs)
        return func(**all_args)

    return wrapper

然后:

@app.route('/mypath')
@map_args
def handler(submission_id, grader, grading_factor, ...):
    """the remaining logic"""

这与Flask对view_args的处理方式类似,不同之处在于它没有进行任何类型的转换,这种转换太窄而无法包含。

答案 2 :(得分:1)

首先,我认为你的做法没有任何问题。但是,您可以采取几种不同的方法;第一个是从request获取参数的调用:

from flask import request

# ...

def getRequestArg(name, *args):
    return request.args.get(name, *args)

submission_id = getRequestArg('submission_id')
grader = getRequestArg('grader')
grading_factor = float(getRequestArg('grading_factor'))
answer_key = getRequestArg('answer_key')
submission_key = getRequestArg('submission_key')

如果您不需要将这些变量分别作为单独的局部变量,则可以将它们全部存储在dict中:

from flask import request

# ...

args = {}
arg_names = ('submission_id', 'grader', 'grading_factor', 'answer_key', 'submission_key')
for arg in arg_names:
    args[arg] = request.args.get(arg)