[英]AJAX-like non-blocking asynchronous Python requests
I looked through numerous questions and answers but none work for me. 我浏览了许多问题和答案,但没有一个对我有用。 Is there a way to achieve AJAX-like functionality in Python?
有没有办法在Python中实现类似AJAX的功能?
Let's say you have this setup: 假设您有以下设置:
url = "http://httpbin.org/delay/5"
print(requests.get(url))
foo()
As the requests.get
blocks code execution, foo()
won't trigger until you got a server response. 由于
requests.get
阻止代码执行,因此在收到服务器响应之前,不会触发foo()
。
In Javascript, for example, the script continues working: 例如,在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()
I tried grequests
, but it still hangs until the whole queue is completed. 我尝试了
grequests
,但是它仍然挂起,直到整个队列完成。
If you are able to use Python 3, take a look at aiohttp . 如果您能够使用Python 3,请查看aiohttp 。 It allows you to make and handle asynchronous requests like:
它允许您发出和处理异步请求,例如:
async with aiohttp.ClientSession() as session:
async with session.get('https://api.github.com/events') as resp:
print(resp.status)
print(await resp.text()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.