我正在尋找一個方式做Perl的HTTP ::異步模塊的next_response方法的Python相當於Perl的HTTP :: Async-> next_response
的HTTP相當於::異步模塊不產卵任何背景的線程,也不使用任何回調。相反,每當有人(在我的情況下,主線程)調用對象的next_response時,目前爲止已經接收到的所有數據都被讀取(阻塞,但是它是隻處理已經接收的數據的瞬時數據)。如果這是響應的結束,那麼next_response將返回一個HTTP :: Response對象,否則它會返回undef。該模塊的
使用看起來像(僞):
request = HTTP::Async(url)
do:
response = request->next_response()
if not response:
sleep 5 # or process events or whatever
while not response
# Do things with response
據我所看到的,Python的urllib的或http.client不支持這種風格。至於爲什麼我想這樣做:
- 這是一個嵌入式Python環境,我不能派生線程,也不會產生任何Python。
- 我只限於一個實際上是嵌入應用程序線程的線程。這意味着我不能有任何延遲的回調 - 應用程序決定何時讓我的Python代碼運行。我所能做的就是請求嵌入式應用程序每隔50毫秒調用一次我選擇的回調函數。
有沒有辦法在Python中做到這一點?
以供參考,這是Perl代碼,我現在和我期待端口到Python的例子:
httpAsync = HTTP::Async->new()
sub httpRequestAsync {
my ($url, $callback) = @_; # $callback will be called with the response text
$httpAsync->add(new HTTP::Request(GET => $url));
# create_timer causes the embedding application to call the supplied callback every 50ms
application::create_timer(50, sub {
my $timer_result = application::keep_timer;
my $response = $httpAsync->next_response;
if ($response) {
my $responseText = $response->decoded_content;
if ($responseText) {
$callback->($responseText);
}
$timer_result = application::remove_timer;
}
# Returning application::keep_timer will preserve the timer to be called again.
# Returning application::remove_timer will remove the timer.
return $timer_result;
});
}
httpRequestAsync('http://www.example.com/', sub {
my $responseText = $_[0];
application::display($responseText);
});
編輯:由於這是一個嵌入式Python實例,我我會採取所有我能得到的選擇(標準庫或其他部分),因爲我必須對它們進行評估,以確保它們可以在我的特定限制條件下運行。
謝謝,但正如我在說問題,嵌入環境的限制禁止我啓動新線程。 – Arnavion
因此,刪除線程部分,這對我來說只是一個方便的事情。 – Torxed
這是一個「你能做什麼」的答案,修改它,嘗試一下,並繞過。 – Torxed