【发布时间】:2023-03-26 13:54:01
【问题描述】:
我查看了许多问题和答案,但没有一个对我有用。 有没有办法在 Python 中实现类似 AJAX 的功能?
假设你有这样的设置:
url = "http://httpbin.org/delay/5"
print(requests.get(url))
foo()
由于requests.get 阻止代码执行,foo() 在您得到服务器响应之前不会触发。
例如,在 Javascript 中,脚本会继续工作:
var requests = {
get: function(url, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
}
function response_goes_through_here(r) {
console.log(r.responseText);
}
var url = "http://httpbin.org/delay/5"
requests.get(url, response_goes_through_here)
foo()
我试过grequests,但它仍然挂起,直到整个队列完成。
【问题讨论】:
标签: python asynchronous python-requests