angularjs 如何在Python的Flask中识别通过AJAX发出的请求?

jmp7cifd  于 6个月前  发布在  Angular
关注(0)|答案(4)|浏览(64)

我想检测浏览器是否通过AJAX(AngularJS)发出了请求,以便我可以返回JSON数组,或者我是否必须呈现模板。如何做到这一点?

cnwbcb6i

cnwbcb6i1#

Flask在request对象中带有一个is_xhr属性。

from flask import request
@app.route('/', methods=['GET', 'POST'])
def home_page():
    if request.is_xhr:
        context = controllers.get_default_context()
        return render_template('home.html', **context)

字符串

**注意:**此解决方案已弃用,不再可行。

ntjbwcob

ntjbwcob2#

对于未来的读者:我做的是下面这样的:

request_xhr_key = request.headers.get('X-Requested-With')
if request_xhr_key and request_xhr_key == 'XMLHttpRequest':
   #mystuff

   return result
abort(404,description="only xhlhttprequest is allowed")

字符串
这将给予一个404错误,如果请求头不包含“XMLHttpRequest”值。

vbopmzt1

vbopmzt13#

没有任何方法可以确定一个请求是否是由一个代理提出的。
我发现对我有效的方法是简单地为xhr请求包含一个get参数,而在非xhr请求中省略该参数。
举例来说:

  • XHR请求:example.com/search?q=Boots&api=1
  • 其他请求:example.com/search?q=Boots
8e2ybdfx

8e2ybdfx4#

我用了这个,它工作得很好:

if request.method == 'POST' and request.headers.get('X-Requested-With') == 'XMLHttpRequest':
    current_app.logger.info('Recognized an AJAX request!')
    # rest of code to handle initial page request

字符串

相关问题