检查请求是否是 Python 中的 AJAX

2022-01-15 00:00:00 python http-headers xmlhttprequest ajax

有没有办法在 Python 中检查请求是否为 AJAX?

Is there a way to check if a request is AJAX in Python?

相当于 PHP 的 $_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest'?

The equivalent of PHP's $_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest'?

推荐答案

如果 AJAX 框架在其请求中设置 X-Requested-With 标头,那么您将能够使用该标头来检测 AJAX 调用.这取决于客户端框架.

If the AJAX framework sets the X-Requested-With header in its requests, then you will be able to use that header to detect AJAX calls. It's up to the client-side framework to do this.

获取 HTTP 标头取决于您选择的 Python 框架.在 Django 中,request 对象有一个 is_ajax方法可以直接使用.

Getting hold of the HTTP headers depends on your Python framework of choice. In Django, the request object has an is_ajax method you can use directly.

相关文章