类似于AJAX的非阻塞异步Python请求 [英] AJAX-like non-blocking asynchronous Python requests

查看:68
本文介绍了类似于AJAX的非阻塞异步Python请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我浏览了许多问题和答案,但没有一个对我有用.有没有办法在Python中实现类似AJAX的功能?

I looked through numerous questions and answers but none work for me. Is there a way to achieve AJAX-like functionality in Python?

假设您具有以下设置:

url = "http://httpbin.org/delay/5"
print(requests.get(url))
foo()

由于 requests.get 阻止了代码执行,因此 foo()不会触发,直到获得服务器响应为止.

As the requests.get blocks code execution, foo() won't trigger until you got a server response.

例如,在Javascript中,脚本可以继续工作:

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()

我尝试了 grequests ,但是它仍然挂起,直到整个队列完成.

I tried grequests, but it still hangs until the whole queue is completed.

推荐答案

如果您能够使用Python 3,请查看 aiohttp .它使您可以发出和处理异步请求,例如:

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()

这篇关于类似于AJAX的非阻塞异步Python请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆