How to get the mtime file of a remote file before uploading it to Ruby?

I have the code below that just downloads the file and saves it. I want to run it every 30 seconds and check if the mtime file of the remote file has changed and upload it if there is one. I will create a thread that will sleep 30 seconds after each iteration of an infinite loop for this purpose, but; how to check remote mtime file without downloading it?

Net::HTTP.start($xmlServerHostname) { |http| resp = http.get($xmlServerPath+"levels.xml") open("levels.xml", "w") { |file| file.write(resp.body) } } 
+5
source share
3 answers

Before you do http.get http.head , which requests only headers without loading the body (i.e. the contents of the file) then check to see if the value of the last modified header has changed.

eg.

 resp = http.head(($xmlServerPath+"levels.xml") last_modified = resp['last-modified'] if last_modified != previous_last_modified # file has changed end 
+8
source

You can try sending an If-Modified-Since header with a correctly formatted date.

If the server supports it, it can only respond with 304 Not Modified (without any content) or full content if the file has been modified.

+4
source

The Net::HTTP 2.6.5 white papers have a concrete example of If-Modified-Since mentioned by fooobar.com/questions/1292123 / ...

 uri = URI('http://example.com/cached_response') file = File.stat 'cached_response' req = Net::HTTP::Get.new(uri) req['If-Modified-Since'] = file.mtime.rfc2822 res = Net::HTTP.start(uri.hostname, uri.port) {|http| http.request(req) } open 'cached_response', 'w' do |io| io.write res.body end if res.is_a?(Net::HTTPSuccess) 

Here is the complete script that actually runs:

 #!/usr/bin/env ruby require 'net/http' require 'time' uri = URI('https://upload.wikimedia.org/wikipedia/commons/thumb/9/95/Illumina_iSeq_100_flow_cell_top.jpg/451px-Illumina_iSeq_100_flow_cell_top.jpg') file_path = 'cached_response' req = Net::HTTP::Get.new(uri) if File.file?(file_path) req['If-Modified-Since'] = File.stat(file_path).mtime.rfc2822 end res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) {|http| http.request(req) } if res.is_a? Net::HTTPSuccess File.open(file_path, 'w') {|io| io.write res.body } end 

but TODO updates the file every time, although Wikimedia seems to interpret If-Modified-Since : https://wikitech.wikimedia.org/wiki/MediaWiki_caching

0
source

All Articles