簡體   English   中英

類似於AJAX的非阻塞異步Python請求

[英]AJAX-like non-blocking asynchronous Python requests

我瀏覽了許多問題和答案,但沒有一個對我有用。 有沒有辦法在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 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM