【发布时间】:2013-05-12 05:57:55
【问题描述】:
我正在寻找一种与 Perl 的 HTTP::Async 模块的 next_response 方法等效的方法
HTTP::Async 模块不产生任何后台线程,也不使用任何回调。相反,每次任何人(在我的例子中,主线程)在对象上调用 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 实例,我将采用所有我能获得的替代方案(标准库的一部分或其他),因为我必须评估所有这些替代方案以确保它们可以运行在我的特殊限制下。
【问题讨论】:
标签: python perl http asynchronous python-3.x