I looked through numerous questions and answers but none work for me. Is there a way to achieve AJAX-like functionality in Python?
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.
In Javascript, for example, the script continues working:
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.
If you are able to use Python 3, take a look at 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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.