我正在寻找一种方法来实现类似于Perl的HTTP::Async模块中next_response方法的功能。
HTTP::Async模块不会生成任何后台线程,也不使用任何回调函数。相反,每当任何人(在我的情况下是主线程)在对象上调用next_response时,已由操作系统接收到的所有数据都将被读取(阻塞,但瞬间完成,因为它只处理已经接收到的数据)。如果这是响应的结尾,则next_response返回一个HTTP::Response对象,否则返回undef。
使用此模块的示例代码如下(伪代码):
据我所知,Python的urllib或http.client不支持这种样式。至于为什么我想以这种方式做:
- 这是用于嵌入式Python环境的,我无法启动线程,也不能让Python生成任何线程。 - 我只能使用一个线程,而实际上这个线程是嵌入应用程序的线程。这意味着我也不能有任何延迟的回调——应用程序决定何时运行我的Python代码。我所能做的就是请求嵌入式应用程序每50毫秒调用我选择的回调函数。 在Python中有没有办法做到这一点?
供参考,以下是我目前拥有的Perl代码,并且我希望将其移植到Python中:
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实例的,我将尽可能提供所有可行的选择(包括标准库或其他选择),因为我必须评估它们以确保它们可以在我的特定限制下运行。
soup = BeautifulSoup(self.inbuffer)
,然后就有一个完美的对象可以获取和处理数据。除此之外,如果不是通过http://docs.python.org/2/library/htmlparser.html手动构建,你就必须自己构建。 - Torxed