在 Rack 应用程序上提供存储在 S3 上的 HTML 文件 [英] Serve HTML files stored on S3 on a Rack app

查看:43
本文介绍了在 Rack 应用程序上提供存储在 S3 上的 HTML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 S3 上存储了一些 HTML 文档,如下所示:

Say I have some HTML documents stored on S3 likes this:

我想用 Rack(最好是 Sinatra)应用程序提供这些服务,映射以下路由:

I'd like to serve these with a Rack (preferably Sinatra) application, mapping the following routes:

get "/posts/:id" do
 render "http://alan.aws-s3-bla-bla.com/posts/#{params[:id]}.html"
end

get "/posts/:posts_id/comments/:comments_id" do
 render "http://alan.aws-s3-bla-bla.com/posts/#{params[:posts_id]}/comments/#{params[:comments_id}.html"
end

这是个好主意吗?我该怎么做?

Is this a good idea? How would I do it?

推荐答案

在您抓取文件时显然需要等待,因此您可以缓存它或设置 etags 等来帮助解决这个问题.我想这取决于您想要等待多长时间以及访问它的频率、它的大小等是否值得在本地或远程存储 HTML.只有你能做到这一点.

There would obviously be a wait while you grabbed the file, so you could cache it or set etags etc to help with that. I suppose it depends on how long you want to wait and how often it is accessed, its size etc as to whether it's worth storing the HTML locally or remotely. Only you can work that bit out.

如果块中的最后一个表达式是一个会自动渲染的字符串,那么只要您将文件作为字符串打开,就不需要调用 render.

If the last expression in the block is a string that will automatically be rendered, so there's no need to call render as long as you've opened the file as a string.

以下是获取外部文件并将其放入临时文件的方法:

Here's how to grab an external file and put it into a tempfile:

require 'faraday'
require 'faraday_middleware'
#require 'faraday/adapter/typhoeus' # see https://github.com/typhoeus/typhoeus/issues/226#issuecomment-9919517 if you get a problem with the requiring
require 'typhoeus/adapters/faraday'

configure do
  Faraday.default_connection = Faraday::Connection.new( 
    :headers => { :accept =>  'text/plain', # maybe this is wrong
    :user_agent => "Sinatra via Faraday"}
  ) do |conn|
    conn.use Faraday::Adapter::Typhoeus
  end
end

helpers do
  def grab_external_html( url )
    response = Faraday.get url # you'll need to supply this variable somehow, your choice
    filename = url # perhaps change this a bit
    tempfile = Tempfile.open(filename, 'wb') { |fp| fp.write(response.body) }
  end
end

get "/posts/:whatever/" do
  tempfile = grab_external_html whatever # surely you'd do a bit more here…
  tempfile.read
end

这可能会奏效.您可能还想考虑关闭该临时文件,但垃圾收集器和操作系统应该处理它.

This might work. You may also want to think about closing that tempfile, but the garbage collector and the OS should take care of it.

这篇关于在 Rack 应用程序上提供存储在 S3 上的 HTML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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