Skip to content

Commit

Permalink
add cache control on json requests
Browse files Browse the repository at this point in the history
  • Loading branch information
alx committed Jul 16, 2011
1 parent 1c50307 commit 49431e4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
1 change: 1 addition & 0 deletions json_server/.gitignore
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ log/*
*.swp *.swp
*.swo *.swo
tmp tmp
cache
22 changes: 16 additions & 6 deletions json_server/lib/json_parser.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
require 'net/http' require 'net/http'
require 'json' require 'json'
require 'pp' require 'pp'

require 'fileutils'


def create_name_table def create_name_table
depute_seats = Array.new(650) depute_seats = Array.new(650)
Expand Down Expand Up @@ -33,11 +33,21 @@ def create_name_table


def api_json(json_url) def api_json(json_url)
url = URI.parse(json_url) url = URI.parse(json_url)
req = Net::HTTP::Get.new(url.path) cached_file = File.join(File.dirname(__FILE__), "/../cache/", url.path)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req) if File.exists? cached_file
} return JSON.load(File.open(cached_file))
return JSON.parse(res.body) else
req = Net::HTTP::Get.new(url.path)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}

FileUtils.mkdir_p File.dirname(cached_file)
File.open(cached_file, "w"){|file| file.write(res.body)}

return JSON.parse(res.body)
end
end end


def parse_synthese(date) def parse_synthese(date)
Expand Down

0 comments on commit 49431e4

Please sign in to comment.