Merge pull request #915 from xhh/ruby-file-response

[Ruby] Support file downloading for Ruby API client
This commit is contained in:
wing328 2015-07-13 14:50:40 +08:00
commit 38760d2aa1
11 changed files with 121 additions and 37 deletions

View File

@ -61,6 +61,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("List", "Array"); typeMapping.put("List", "Array");
typeMapping.put("map", "Hash"); typeMapping.put("map", "Hash");
typeMapping.put("object", "Object"); typeMapping.put("object", "Object");
typeMapping.put("file", "File");
// remove modelPackage and apiPackage added by default // remove modelPackage and apiPackage added by default
cliOptions.clear(); cliOptions.clear();

View File

@ -3,6 +3,18 @@ module {{moduleName}}
class Configuration class Configuration
attr_accessor :format, :api_key, :api_key_prefix, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent, :verify_ssl attr_accessor :format, :api_key, :api_key_prefix, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent, :verify_ssl
# Defines the temporary folder to store downloaded files
# (for API endpoints that have file response).
# Default to use `Tempfile`.
#
# @return [String]
attr_accessor :temp_folder_path
# Defines the headers to be used in HTTP requests of all API calls by default.
#
# @return [Hash]
attr_accessor :default_headers
# Defaults go in here.. # Defaults go in here..
def initialize def initialize
@format = 'json' @format = 'json'
@ -14,6 +26,11 @@ module {{moduleName}}
@force_ending_format = false @force_ending_format = false
@camelize_params = true @camelize_params = true
@default_headers = {
'Content-Type' => "application/#{@format.downcase}",
'User-Agent' => @user_agent
}
# keys for API key authentication (param-name => api-key) # keys for API key authentication (param-name => api-key)
@api_key = {} @api_key = {}
# api-key prefix for API key authentication, e.g. "Bearer" (param-name => api-key-prefix) # api-key prefix for API key authentication, e.g. "Bearer" (param-name => api-key-prefix)

View File

@ -10,27 +10,22 @@ module {{moduleName}}
# All requests must have an HTTP method and a path # All requests must have an HTTP method and a path
# Optionals parameters are :params, :headers, :body, :format, :host # Optionals parameters are :params, :headers, :body, :format, :host
def initialize(http_method, path, attributes={}) def initialize(http_method, path, attributes={})
attributes[:format] ||= Swagger.configuration.format @http_method = http_method.to_sym
attributes[:params] ||= {} @path = path
# Set default headers attributes.each do |name, value|
default_headers = { send("#{name.to_s.underscore.to_sym}=", value)
'Content-Type' => "application/#{attributes[:format].downcase}", end
'User-Agent' => Swagger.configuration.user_agent
}
# Merge argument headers into defaults @format ||= Swagger.configuration.format
attributes[:headers] = default_headers.merge(attributes[:headers] || {}) @params ||= {}
# Apply default headers
@headers = Swagger.configuration.default_headers.merge(@headers || {})
# Stick in the auth token if there is one # Stick in the auth token if there is one
if Swagger.authenticated? if Swagger.authenticated?
attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) @headers.merge!({:auth_token => Swagger.configuration.auth_token})
end
self.http_method = http_method.to_sym
self.path = path
attributes.each do |name, value|
send("#{name.to_s.underscore.to_sym}=", value)
end end
update_params_for_auth! update_params_for_auth!

View File

@ -3,6 +3,7 @@ module {{moduleName}}
class Response class Response
require 'json' require 'json'
require 'date' require 'date'
require 'tempfile'
attr_accessor :raw attr_accessor :raw
@ -31,8 +32,11 @@ module {{moduleName}}
def deserialize(return_type) def deserialize(return_type)
return nil if body.blank? return nil if body.blank?
# handle file downloading - save response body into a tmp file and return the File instance
return download_file if return_type == 'File'
# ensuring a default content type # ensuring a default content type
content_type = raw.headers_hash['Content-Type'] || 'application/json' content_type = raw.headers['Content-Type'] || 'application/json'
unless content_type.start_with?('application/json') unless content_type.start_with?('application/json')
fail "Content-Type is not supported: #{content_type}" fail "Content-Type is not supported: #{content_type}"
@ -82,6 +86,28 @@ module {{moduleName}}
end end
end end
# Save response body into a file in (the defined) temporary folder, using the filename
# from the "Content-Disposition" header if provided, otherwise a random filename.
#
# @see Configuration#temp_folder_path
# @return [File] the file downloaded
def download_file
tmp_file = Tempfile.new '', Swagger.configuration.temp_folder_path
content_disposition = raw.headers['Content-Disposition']
if content_disposition
filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
path = File.join File.dirname(tmp_file), filename
else
path = tmp_file.path
end
# close and delete temp file
tmp_file.close!
File.open(path, 'w') { |file| file.write(raw.body) }
Swagger.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards"
return File.new(path)
end
# `headers_hash` is a Typhoeus-specific extension of Hash, # `headers_hash` is a Typhoeus-specific extension of Hash,
# so simplify it back into a regular old Hash. # so simplify it back into a regular old Hash.
def headers def headers

View File

@ -22,5 +22,6 @@ require '{{importPath}}'
module {{moduleName}} module {{moduleName}}
# Initialize the default configuration # Initialize the default configuration
Swagger.configuration ||= Swagger::Configuration.new Swagger.configuration = Swagger::Configuration.new
Swagger.configure { |config| }
end end

View File

@ -22,5 +22,6 @@ require 'swagger_client/api/store_api'
module SwaggerClient module SwaggerClient
# Initialize the default configuration # Initialize the default configuration
Swagger.configuration ||= Swagger::Configuration.new Swagger.configuration = Swagger::Configuration.new
Swagger.configure { |config| }
end end

View File

@ -286,7 +286,7 @@ module SwaggerClient
# @param pet_id ID of pet to update # @param pet_id ID of pet to update
# @param [Hash] opts the optional parameters # @param [Hash] opts the optional parameters
# @option opts [String] :additional_metadata Additional data to pass to server # @option opts [String] :additional_metadata Additional data to pass to server
# @option opts [file] :file file to upload # @option opts [File] :file file to upload
# @return [nil] # @return [nil]
def self.upload_file(pet_id, opts = {}) def self.upload_file(pet_id, opts = {})

View File

@ -3,6 +3,18 @@ module SwaggerClient
class Configuration class Configuration
attr_accessor :format, :api_key, :api_key_prefix, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent, :verify_ssl attr_accessor :format, :api_key, :api_key_prefix, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent, :verify_ssl
# Defines the temporary folder to store downloaded files
# (for API endpoints that have file response).
# Default to use `Tempfile`.
#
# @return [String]
attr_accessor :temp_folder_path
# Defines the headers to be used in HTTP requests of all API calls by default.
#
# @return [Hash]
attr_accessor :default_headers
# Defaults go in here.. # Defaults go in here..
def initialize def initialize
@format = 'json' @format = 'json'
@ -14,6 +26,11 @@ module SwaggerClient
@force_ending_format = false @force_ending_format = false
@camelize_params = true @camelize_params = true
@default_headers = {
'Content-Type' => "application/#{@format.downcase}",
'User-Agent' => @user_agent
}
# keys for API key authentication (param-name => api-key) # keys for API key authentication (param-name => api-key)
@api_key = {} @api_key = {}
# api-key prefix for API key authentication, e.g. "Bearer" (param-name => api-key-prefix) # api-key prefix for API key authentication, e.g. "Bearer" (param-name => api-key-prefix)

View File

@ -10,27 +10,22 @@ module SwaggerClient
# All requests must have an HTTP method and a path # All requests must have an HTTP method and a path
# Optionals parameters are :params, :headers, :body, :format, :host # Optionals parameters are :params, :headers, :body, :format, :host
def initialize(http_method, path, attributes={}) def initialize(http_method, path, attributes={})
attributes[:format] ||= Swagger.configuration.format @http_method = http_method.to_sym
attributes[:params] ||= {} @path = path
# Set default headers attributes.each do |name, value|
default_headers = { send("#{name.to_s.underscore.to_sym}=", value)
'Content-Type' => "application/#{attributes[:format].downcase}", end
'User-Agent' => Swagger.configuration.user_agent
}
# Merge argument headers into defaults @format ||= Swagger.configuration.format
attributes[:headers] = default_headers.merge(attributes[:headers] || {}) @params ||= {}
# Apply default headers
@headers = Swagger.configuration.default_headers.merge(@headers || {})
# Stick in the auth token if there is one # Stick in the auth token if there is one
if Swagger.authenticated? if Swagger.authenticated?
attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) @headers.merge!({:auth_token => Swagger.configuration.auth_token})
end
self.http_method = http_method.to_sym
self.path = path
attributes.each do |name, value|
send("#{name.to_s.underscore.to_sym}=", value)
end end
update_params_for_auth! update_params_for_auth!

View File

@ -3,6 +3,7 @@ module SwaggerClient
class Response class Response
require 'json' require 'json'
require 'date' require 'date'
require 'tempfile'
attr_accessor :raw attr_accessor :raw
@ -31,8 +32,11 @@ module SwaggerClient
def deserialize(return_type) def deserialize(return_type)
return nil if body.blank? return nil if body.blank?
# handle file downloading - save response body into a tmp file and return the File instance
return download_file if return_type == 'File'
# ensuring a default content type # ensuring a default content type
content_type = raw.headers_hash['Content-Type'] || 'application/json' content_type = raw.headers['Content-Type'] || 'application/json'
unless content_type.start_with?('application/json') unless content_type.start_with?('application/json')
fail "Content-Type is not supported: #{content_type}" fail "Content-Type is not supported: #{content_type}"
@ -82,6 +86,28 @@ module SwaggerClient
end end
end end
# Save response body into a file in (the defined) temporary folder, using the filename
# from the "Content-Disposition" header if provided, otherwise a random filename.
#
# @see Configuration#temp_folder_path
# @return [File] the file downloaded
def download_file
tmp_file = Tempfile.new '', Swagger.configuration.temp_folder_path
content_disposition = raw.headers['Content-Disposition']
if content_disposition
filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
path = File.join File.dirname(tmp_file), filename
else
path = tmp_file.path
end
# close and delete temp file
tmp_file.close!
File.open(path, 'w') { |file| file.write(raw.body) }
Swagger.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards"
return File.new(path)
end
# `headers_hash` is a Typhoeus-specific extension of Hash, # `headers_hash` is a Typhoeus-specific extension of Hash,
# so simplify it back into a regular old Hash. # so simplify it back into a regular old Hash.
def headers def headers

View File

@ -19,10 +19,15 @@ describe SwaggerClient::Swagger::Request do
end end
describe "initialization" do describe "initialization" do
it "sets default response format to json" do it "sets default response format to json" do
@request.format.should == 'json' @request.format.should == 'json'
end end
it "sets default headers correctly" do
@request.headers.should == {'Content-Type' => 'application/json', 'User-Agent' => 'ruby-swagger-1.0.0'}
end
it "allows params to be nil" do it "allows params to be nil" do
@request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, :params => nil) @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, :params => nil)
@request.query_string.should == "" @request.query_string.should == ""