【问题标题】:AJAX-like non-blocking asynchronous Python requests类 AJAX 的非阻塞异步 Python 请求
【发布时间】: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


    【解决方案1】:

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

    async with aiohttp.ClientSession() as session:
        async with session.get('https://api.github.com/events') as resp:
            print(resp.status)
            print(await resp.text()
    

    【讨论】:

    • 它会阻塞线程吗?我看到的大多数示例在收到响应之前都会停止代码执行。
    猜你喜欢
    • 2014-07-29
    • 1970-01-01
    • 2012-10-14
    • 2021-11-14
    • 1970-01-01
    • 2020-03-04
    • 2018-04-06
    相关资源
    最近更新 更多