Permalink
Browse files

add cache control on json requests

  • Loading branch information...
alx committed Jul 16, 2011
1 parent 1c50307 commit 49431e4cf41dd2a0d13977c43e1e5e5b975baeae
Showing with 17 additions and 6 deletions.
  1. +1 −0 json_server/.gitignore
  2. +16 −6 json_server/lib/json_parser.rb
View
@@ -5,3 +5,4 @@ log/*
*.swp
*.swo
tmp
+cache
@@ -2,7 +2,7 @@
require 'net/http'
require 'json'
require 'pp'
-
+require 'fileutils'
def create_name_table
depute_seats = Array.new(650)
@@ -33,11 +33,21 @@ def create_name_table
def api_json(json_url)
url = URI.parse(json_url)
- req = Net::HTTP::Get.new(url.path)
- res = Net::HTTP.start(url.host, url.port) {|http|
- http.request(req)
- }
- return JSON.parse(res.body)
+ cached_file = File.join(File.dirname(__FILE__), "/../cache/", url.path)
+
+ if File.exists? cached_file
+ return JSON.load(File.open(cached_file))
+ 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
def parse_synthese(date)

0 comments on commit 49431e4

Please sign in to comment.