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("map", "Hash");
typeMapping.put("object", "Object");
typeMapping.put("file", "File");
// remove modelPackage and apiPackage added by default
cliOptions.clear();

View File

@ -3,6 +3,18 @@ module {{moduleName}}
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
# 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..
def initialize
@format = 'json'
@ -14,6 +26,11 @@ module {{moduleName}}
@force_ending_format = false
@camelize_params = true
@default_headers = {
'Content-Type' => "application/#{@format.downcase}",
'User-Agent' => @user_agent
}
# keys for API key authentication (param-name => api-key)
@api_key = {}
# 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
# Optionals parameters are :params, :headers, :body, :format, :host
def initialize(http_method, path, attributes={})
attributes[:format] ||= Swagger.configuration.format
attributes[:params] ||= {}
@http_method = http_method.to_sym
@path = path
# Set default headers
default_headers = {
'Content-Type' => "application/#{attributes[:format].downcase}",
'User-Agent' => Swagger.configuration.user_agent
}
attributes.each do |name, value|
send("#{name.to_s.underscore.to_sym}=", value)
end
# Merge argument headers into defaults
attributes[:headers] = default_headers.merge(attributes[:headers] || {})
@format ||= Swagger.configuration.format
@params ||= {}
# Apply default headers
@headers = Swagger.configuration.default_headers.merge(@headers || {})
# Stick in the auth token if there is one
if Swagger.authenticated?
attributes[: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)
@headers.merge!({:auth_token => Swagger.configuration.auth_token})
end
update_params_for_auth!

View File

@ -3,6 +3,7 @@ module {{moduleName}}
class Response
require 'json'
require 'date'
require 'tempfile'
attr_accessor :raw
@ -31,8 +32,11 @@ module {{moduleName}}
def deserialize(return_type)
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
content_type = raw.headers_hash['Content-Type'] || 'application/json'
content_type = raw.headers['Content-Type'] || 'application/json'
unless content_type.start_with?('application/json')
fail "Content-Type is not supported: #{content_type}"
@ -82,6 +86,28 @@ module {{moduleName}}
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,
# so simplify it back into a regular old Hash.
def headers

View File

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

View File

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

View File

@ -286,7 +286,7 @@ module SwaggerClient
# @param pet_id ID of pet to update
# @param [Hash] opts the optional parameters
# @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]
def self.upload_file(pet_id, opts = {})

View File

@ -3,6 +3,18 @@ module SwaggerClient
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
# 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..
def initialize
@format = 'json'
@ -14,6 +26,11 @@ module SwaggerClient
@force_ending_format = false
@camelize_params = true
@default_headers = {
'Content-Type' => "application/#{@format.downcase}",
'User-Agent' => @user_agent
}
# keys for API key authentication (param-name => api-key)
@api_key = {}
# 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
# Optionals parameters are :params, :headers, :body, :format, :host
def initialize(http_method, path, attributes={})
attributes[:format] ||= Swagger.configuration.format
attributes[:params] ||= {}
@http_method = http_method.to_sym
@path = path
# Set default headers
default_headers = {
'Content-Type' => "application/#{attributes[:format].downcase}",
'User-Agent' => Swagger.configuration.user_agent
}
attributes.each do |name, value|
send("#{name.to_s.underscore.to_sym}=", value)
end
# Merge argument headers into defaults
attributes[:headers] = default_headers.merge(attributes[:headers] || {})
@format ||= Swagger.configuration.format
@params ||= {}
# Apply default headers
@headers = Swagger.configuration.default_headers.merge(@headers || {})
# Stick in the auth token if there is one
if Swagger.authenticated?
attributes[: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)
@headers.merge!({:auth_token => Swagger.configuration.auth_token})
end
update_params_for_auth!

View File

@ -3,6 +3,7 @@ module SwaggerClient
class Response
require 'json'
require 'date'
require 'tempfile'
attr_accessor :raw
@ -31,8 +32,11 @@ module SwaggerClient
def deserialize(return_type)
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
content_type = raw.headers_hash['Content-Type'] || 'application/json'
content_type = raw.headers['Content-Type'] || 'application/json'
unless content_type.start_with?('application/json')
fail "Content-Type is not supported: #{content_type}"
@ -82,6 +86,28 @@ module SwaggerClient
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,
# so simplify it back into a regular old Hash.
def headers

View File

@ -19,10 +19,15 @@ describe SwaggerClient::Swagger::Request do
end
describe "initialization" do
it "sets default response format to json" do
@request.format.should == 'json'
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
@request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, :params => nil)
@request.query_string.should == ""