ruby 要下载和解压缩的Rake任务

gkl3eglg  于 2023-05-17  发布在  Ruby
关注(0)|答案(3)|浏览(130)

我想每周更新一个 * 城市 * 表,以反映世界各地城市的变化。我正在为此创建一个Rake任务。如果可能的话,我希望在不添加其他gem依赖项的情况下完成此操作
压缩文件是一个公开可用的压缩文件,位于geonames.org/15000cities.zip
我的尝试:

require 'net/http'
require 'zip'

namespace :geocities do
  desc "Rake task to fetch Geocities city list every 3 days"
  task :fetch do

    uri = URI('http://download.geonames.org/export/dump/cities15000.zip')
    zipped_folder = Net::HTTP.get(uri) 

    Zip::File.open(zipped_folder) do |unzipped_folder| #erroring here
      unzipped_folder.each do |file|
        Rails.root.join("", "list_of_cities.txt").write(file)
      end
    end
  end
end

rake geocities:fetch返回

rake aborted!
ArgumentError: string contains null byte

如详细所述,我正在尝试解压缩该文件并将其保存到 list_of_cities.txt 文件中。一旦我确定了完成这一任务的方法,我相信我可以弄清楚如何根据文件更新我的数据库。(但是如果你对如何最好地处理实际的数据库更新有意见,除了我计划的方式,我很乐意听到他们。但这似乎是一个完全不同的职位)。

k4aesqcs

k4aesqcs1#

这将把zipped_folder保存到磁盘,然后解压缩并保存其内容:

require 'net/http'                                                              
require 'zip'                                                                   

namespace :geocities do                                                         
  desc "Rake task to fetch Geocities city list every 3 days"                    
  task :fetch do                                                                

    uri = URI('http://download.geonames.org/export/dump/cities15000.zip')                          
    zipped_folder = Net::HTTP.get(uri)                                          

    File.open('cities.zip', 'wb') do |file|                                      
      file.write(zipped_folder)                                                 
    end                                                                         

    zip_file = Zip::File.open('cities.zip')                                     
    zip_file.each do |file|                                                     
      file.extract
    end                                                                         
  end                                                                           
end

这将提取zip文件中的所有文件,在本例中为cities15000.txt
然后,您可以读取cities15000.txt的内容并更新数据库。
如果你想提取到一个不同的文件名,你可以像这样把它传递给file.extract

zip_file.each do |file|                                                     
    file.extract('list_of_cities.txt')
end
dsf9zpds

dsf9zpds2#

我认为不用ruby也可以更容易地完成,只需要使用wgetunzip

namespace :geocities do
  desc "Rake task to fetch Geocities city list every 3 days"
  task :fetch do
     `wget -c --tries=10 http://download.geonames.org/export/dump/cities15000.zip | unzip`
  end
end
wmtdaxz3

wmtdaxz33#

这里有一个从远程URL下载zip到本地并解压缩到tmp文件位置的工作解决方案。

url = 'https://example.com/path/to/your_zip_file.zip'

destination = Rails.root.join('tmp', 'your_zip_file.zip')

system("curl -L -o '#{destination}' '#{url}'")

# Unzip the downloaded file using a system command
system("unzip '#{destination}' -d '#{Rails.root.join('tmp')}'")

相关问题