目前我正在使用以下方式查看请求是否为 AJAX / XHR 。因此,我将返回json数据并在Flask中呈现模板文件。这在我的应用程序中完美地工作。
from flask import request, render_template, jsonify
@cinemascope.route('/cinema')
def cinema():
if request.is_xhr:
cinema = Cinema.query.all()
return jsonify({'cinema_scope': cinema})
return render_template('cinema.html')
但是我觉得这样的问题很少,因为我的应用程序可能会有更多的@ app.routes,并且每次我都必须重复代码(if子句),因此它在可维护性方面失去了作用。
我在考虑这两个选项 -
选项#1 - 编写一个简单的函数来从上面的路径中包装if子句。
选项#2 - 编写一个装饰器,它将确定请求并因此可以从路径调用 - 装饰器将处理代码的冗余部分。到目前为止,我对编写自定义装饰器不太了解,但在阅读之后,它似乎是最好的选择。
采用任何上述方法的任何进一步方向将不胜感激。
基本上我想知道方式 - 所以我可以在每个@ app.route中避免if clause
部分代码。
答案 0 :(得分:4)
我指的是 - 来自http://justindonato.com/notebook/template-or-json-decorator-for-flask.html
这就是我的装饰师的样子
from functools import wraps
def xhr_request_check(template=None):
def decorator_request_parser(f):
@wraps(f)
def decorator_request(*args, **kwargs):
func_data = f(*args, **kwargs)
if request.is_xhr or not template:
return jsonify(func_data)
else:
return render_template(template, **func_data)
return decorator_request
return decorator_request_parser
在我看来,我写过
from flask import request, render_template, jsonify
@catalog.route('/cinema')
@xhr_request_check('cinema.html')
def cinema():
cinema = Cinema.query.all()
return {'cinema_scope': cinema}
现在我只需要为每条路线添加 @xhr_request_check('cinema.html')
,它就能完美运行。
如果有任何人从代码优化角度提供更好的解决方案,请告诉我。
答案 1 :(得分:2)
这样做的方法是创建一个装饰器,它本质上是将函数作为输入并将函数作为输出返回的函数。它们并不是特定于烧瓶,而是一般的python。
以下是烧瓶的示例: How to make a python decorator function in Flask with arguments (for authorization)
答案 2 :(得分:0)
is_xhr
已弃用,但您可以检查Accepts header。