有没有办法将 html 刷新到 Sinatra 中的电线上 [英] Is there a way to flush html to the wire in Sinatra

查看:40
本文介绍了有没有办法将 html 刷新到 Sinatra 中的电线上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行时间很长的 Sinatra 应用程序(网络抓取工具).我希望应用程序在爬虫运行时刷新爬虫进度的结果,而不是在最后.

I have a Sinatra app with a long running process (a web scraper). I'd like the app flush the results of the crawler's progress as the crawler is running instead of at the end.

我已经考虑过分叉请求并用 ajax 做一些奇特的事情,但这是一个非常基本的单页应用程序,它实际上只需要在它发生时将日志输出到浏览器.有什么建议吗?

I've considered forking the request and doing something fancy with ajax but this is a really basic one-pager app that really just needs to output a log to a browser as it's happening. Any suggestions?

推荐答案

更新 (2012-03-21)

从 Sinatra 1.3.0 开始,您可以使用新的流 API:

Update (2012-03-21)

As of Sinatra 1.3.0, you can use the new streaming API:

get '/' do
  stream do |out|
    out << "foo\n"
    sleep 10
    out << "bar\n"
  end
end

旧答案

不幸的是,您没有可以简单地刷新到的流(这不适用于 Rack 中间件).从路由块返回的结果可以简单地响应 each.然后,Rack 处理程序将使用一个块调用 each,并在该块中将主体的给定部分刷新到客户端.

Old Answer

Unfortunately you don't have a stream you can simply flush to (that would not work with Rack middleware). The result returned from a route block can simply respond to each. The Rack handler will then call each with a block and in that block flush the given part of the body to the client.

所有机架响应必须始终响应 each 并且始终将字符串传递给给定的块.如果您只返回一个字符串,Sinatra 会为您处理这个问题.

All rack responses have to always respond to each and always hand strings to the given block. Sinatra takes care of this for you, if you just return a string.

一个简单的流媒体示例是:

A simple streaming example would be:

require 'sinatra'

get '/' do
  result = ["this", " takes", " some", " time"]
  class << result
    def each
      super do |str|
        yield str
        sleep 0.3
      end
    end
  end
  result
end

现在您可以简单地将所有爬取内容放在 each 方法中:

Now you could simply place all your crawling in the each method:

require 'sinatra'

class Crawler
  def initialize(url)
    @url = url
  end

  def each
    yield "opening url\n"
    result = open @url
    yield "seaching for foo\n"
    if result.include? "foo"
      yield "found it\n"
    else
      yield "not there, sorry\n"
    end
  end
end

get '/' do
  Crawler.new 'http://mysite'
end

这篇关于有没有办法将 html 刷新到 Sinatra 中的电线上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆