Class: Patron::Session

Inherits:
Object
  • Object
show all
Defined in:
lib/patron/session.rb,
ext/patron/session_ext.c

Overview

This class represents multiple request/response transactions with an HTTP server. This is the primary API for Patron.

Instance Attribute Summary collapse

WebDAV methods collapse

Basic API methods collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) { ... } ⇒ Session

Create a new Session object for performing requests.

Parameters:

  • args (Hash) (defaults to: {})

    options for the Session (same names as the writable attributes of the Session)

Yields:

  • self



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/patron/session.rb', line 115

def initialize(args = {}, &block)

  # Allows accessors to be set via constructor hash. Ex:  {:base_url => 'www.home.com'}
  args.each do |attribute, value|
    send("#{attribute}=", value)
  end

  # Allows accessors to be set via block.
  if block_given?
    yield self
  end

  @headers ||= {}
  @headers['User-Agent'] ||= Patron.user_agent_string
  @timeout ||= 5
  @connect_timeout ||= 1
  @max_redirects ||= 5
  @auth_type ||= :basic
  @force_ipv4 ||= false
end

Instance Attribute Details

#auth_typeSymbol

Returns the authentication type for the request (:basic, :digest or :token).

Returns:

  • (Symbol)

    the authentication type for the request (:basic, :digest or :token).

See Also:

  • Request#auth_type


75
76
77
# File 'lib/patron/session.rb', line 75

def auth_type
  @auth_type
end

#automatic_content_encodingBoolean

Returns Support automatic Content-Encoding decompression and set liberal Accept-Encoding headers.

Returns:

  • (Boolean)

    Support automatic Content-Encoding decompression and set liberal Accept-Encoding headers



107
108
109
# File 'lib/patron/session.rb', line 107

def automatic_content_encoding
  @automatic_content_encoding
end

#base_urlString

Returns The URL to prepend to all requests.

Returns:

  • (String)

    The URL to prepend to all requests.



53
54
55
# File 'lib/patron/session.rb', line 53

def base_url
  @base_url
end

#buffer_sizeInteger?

Set the buffer size for this request. This option will only be set if buffer_size is non-nil

Returns:

  • (Integer, nil)


94
95
96
# File 'lib/patron/session.rb', line 94

def buffer_size
  @buffer_size
end

#cacertString

Returns path to the CA file used for certificate verification, or nil if CURL default is used.

Returns:

  • (String)

    path to the CA file used for certificate verification, or nil if CURL default is used



86
87
88
# File 'lib/patron/session.rb', line 86

def cacert
  @cacert
end

#connect_timeoutInteger

Returns HTTP connection timeout in seconds. Defaults to 1 second.

Returns:

  • (Integer)

    HTTP connection timeout in seconds. Defaults to 1 second.



42
43
44
# File 'lib/patron/session.rb', line 42

def connect_timeout
  @connect_timeout
end

#default_response_charsetString?

Sets the name of the charset to assume for the response. The argument should be a String that is an acceptable argument for Encoding.find() in Ruby. The variable will only be used if the response does not specify a charset in it's Content-Type header already, if it does that charset will take precedence.

Returns:

  • (String, nil)


101
102
103
# File 'lib/patron/session.rb', line 101

def default_response_charset
  @default_response_charset
end

#force_ipv4Boolean

Returns Force curl to use IPv4.

Returns:

  • (Boolean)

    Force curl to use IPv4



104
105
106
# File 'lib/patron/session.rb', line 104

def force_ipv4
  @force_ipv4
end

#headersHash

Returns headers used in all requests.

Returns:

  • (Hash)

    headers used in all requests.



71
72
73
# File 'lib/patron/session.rb', line 71

def headers
  @headers
end

#ignore_content_lengthBoolean

Returns whether Content-Range and Content-Length headers should be ignored.

Returns:

  • (Boolean)

    whether Content-Range and Content-Length headers should be ignored



89
90
91
# File 'lib/patron/session.rb', line 89

def ignore_content_length
  @ignore_content_length
end

#insecureBoolean

Please consider twice before using this option..

Returns:

  • (Boolean)

    true if SSL certificate verification is disabled.



79
80
81
# File 'lib/patron/session.rb', line 79

def insecure
  @insecure
end

#max_redirectsInteger

Maximum number of redirects to follow Set to 0 to disable and -1 to follow all redirects. Defaults to 5.

Returns:

  • (Integer)


50
51
52
# File 'lib/patron/session.rb', line 50

def max_redirects
  @max_redirects
end

#passwordString?

Password for http authentication

Returns:

  • (String, nil)

    the HTTP basic auth password



61
62
63
# File 'lib/patron/session.rb', line 61

def password
  @password
end

#proxyString

Returns Proxy URL in cURL format ('hostname:8080').

Returns:

  • (String)

    Proxy URL in cURL format ('hostname:8080')



64
65
66
# File 'lib/patron/session.rb', line 64

def proxy
  @proxy
end

#proxy_typeInteger

Returns Proxy type (default is HTTP).

Returns:

  • (Integer)

    Proxy type (default is HTTP)

See Also:



68
69
70
# File 'lib/patron/session.rb', line 68

def proxy_type
  @proxy_type
end

#ssl_versionString

The supported values are nil, "SSLv2", "SSLv3", and "TLSv1".

Returns:

  • (String)

    the SSL version for the requests, or nil if all versions are permitted



83
84
85
# File 'lib/patron/session.rb', line 83

def ssl_version
  @ssl_version
end

#timeoutInteger

Returns HTTP transaction timeout in seconds. Defaults to 5 seconds.

Returns:

  • (Integer)

    HTTP transaction timeout in seconds. Defaults to 5 seconds.



45
46
47
# File 'lib/patron/session.rb', line 45

def timeout
  @timeout
end

#usernameString?

Username for http authentication

Returns:

  • (String, nil)

    the HTTP basic auth username



57
58
59
# File 'lib/patron/session.rb', line 57

def username
  @username
end

Class Method Details

.escape(value) ⇒ Object

Escapes the provided string using libCURL URL escaping functions.

Parameters:

  • value (String)

    plain string to URL-escape @return [String] the escaped string



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'ext/patron/session_ext.c', line 215

static VALUE session_escape(VALUE self, VALUE value) {
  
  VALUE string = StringValue(value);
  char* escaped = NULL;
  VALUE retval = Qnil;

  struct curl_state* state = curl_easy_init();
  escaped = curl_easy_escape(state->handle,
                             RSTRING_PTR(string),
                             (int) RSTRING_LEN(string));

  retval = rb_str_new2(escaped);
  curl_easy_cleanup(state);
  curl_free(escaped);

  return retval;
}

.unescape(value) ⇒ Object

Unescapes the provided string using libCURL URL escaping functions.

Parameters:

  • value (String)

    URL-encoded String to unescape @return [String] unescaped (decoded) string



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'ext/patron/session_ext.c', line 239

static VALUE session_unescape(VALUE self, VALUE value) {
  VALUE string = StringValue(value);
  char* unescaped = NULL;
  VALUE retval = Qnil;

  struct curl_state* state = curl_easy_init();
  unescaped = curl_easy_unescape(state->handle,
                                 RSTRING_PTR(string),
                                 (int) RSTRING_LEN(string),
                                 NULL);

  retval = rb_str_new2(unescaped);
  curl_free(unescaped);
  curl_easy_cleanup(state);

  return retval;
}

Instance Method Details

Turn on cookie handling for this session, storing them in memory by default or in +file+ if specified. The file must be readable and writable. Calling multiple times will add more files. FIXME: what does the empty string actually do here?

Parameters:

  • file (String)

    path to the existing cookie file, or nil to store in memory. @return self



777
778
779
780
781
782
783
784
785
786
787
788
789
790
# File 'ext/patron/session_ext.c', line 777

static VALUE add_cookie_file(VALUE self, VALUE file) {
  struct curl_state *state = get_curl_state(self);
  CURL* curl = state->handle;
  char* file_path = NULL;

  // FIXME: http://websystemsengineering.blogspot.nl/2013/03/curloptcookiefile-vs-curloptcookiejar.html
  file_path = RSTRING_PTR(file);
  if (file_path != NULL && strlen(file_path) != 0) {
    curl_easy_setopt(curl, CURLOPT_COOKIEJAR, file_path);
  }
  curl_easy_setopt(curl, CURLOPT_COOKIEFILE, file_path);

  return self;
}

#build_request(action, url, headers, options = {}) ⇒ Patron::Request

Builds a request object that can be used by ++handle_request++ Note that internally, ++handle_request++ uses instance variables of the Request object, and not it's public methods.

Parameters:

  • action (String)

    the HTTP verb

  • url (#to_s)

    the addition to the base url component, or a complete URL

  • headers (Hash)

    a hash of headers, "Accept" will be automatically set to an empty string if not provided

  • options (Hash) (defaults to: {})

    any overriding options (will shadow the options from the Session object)

Returns:

  • (Patron::Request)

    the request that will be passed to ++handle_request++



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/patron/session.rb', line 355

def build_request(action, url, headers, options = {})
  # If the Expect header isn't set uploads are really slow
  headers['Expect'] ||= ''

  Request.new.tap do |req|
    req.action                 = action
    req.headers                = self.headers.merge headers
    req.automatic_content_encoding = options.fetch :automatic_content_encoding, self.automatic_content_encoding
    req.timeout                = options.fetch :timeout,               self.timeout
    req.connect_timeout        = options.fetch :connect_timeout,       self.connect_timeout
    req.force_ipv4             = options.fetch :force_ipv4,            self.force_ipv4
    req.max_redirects          = options.fetch :max_redirects,         self.max_redirects
    req.username               = options.fetch :username,              self.username
    req.password               = options.fetch :password,              self.password
    req.proxy                  = options.fetch :proxy,                 self.proxy
    req.proxy_type             = options.fetch :proxy_type,            self.proxy_type
    req.auth_type              = options.fetch :auth_type,             self.auth_type
    req.insecure               = options.fetch :insecure,              self.insecure
    req.ssl_version            = options.fetch :ssl_version,           self.ssl_version
    req.cacert                 = options.fetch :cacert,                self.cacert
    req.ignore_content_length  = options.fetch :ignore_content_length, self.ignore_content_length
    req.buffer_size            = options.fetch :buffer_size,           self.buffer_size
    req.multipart              = options[:multipart]
    req.upload_data            = options[:data]
    req.file_name              = options[:file]

    base_url = self.base_url.to_s
    url = url.to_s
    raise ArgumentError, "Empty URL" if base_url.empty? && url.empty?
    uri = URI.parse(base_url.empty? ? url : File.join(base_url, url))
    query = uri.query.to_s.split('&')
    query += options[:query].is_a?(Hash) ? Util.build_query_pairs_from_hash(options[:query]) : options[:query].to_s.split('&')
    uri.query = query.join('&')
    uri.query = nil if uri.query.empty?
    url = uri.to_s
    req.url = url
  end
end

#copy(url, dest, headers = {}) ⇒ Patron::Response

Sends a WebDAV COPY request to the specified +url+.

Parameters:

  • url (String)

    the URL to copy

  • dest (String)

    the URL of the COPY destination

  • headers (Hash) (defaults to: {})

    the hash of header keys to values

Returns:



311
312
313
314
# File 'lib/patron/session.rb', line 311

def copy(url, dest, headers = {})
  headers['Destination'] = dest
  request(:copy, url, headers)
end

#delete(url, headers = {}) ⇒ Patron::Response

Same as #get but performs a DELETE request.

Notice: this method doesn't accept any data argument: if you need to send data with a delete request (as might be needed for ElasticSearch), please, use the #request method.

Parameters:

  • url (String)

    the URL to fetch

  • headers (Hash) (defaults to: {})

    the hash of header keys to values

Returns:



221
222
223
# File 'lib/patron/session.rb', line 221

def delete(url, headers = {})
  request(:delete, url, headers)
end

#enable_debug(file = nil) ⇒ Object

TODO:

Change to an assignment of an IO object

Enable debug output to stderr or to specified file.

Parameters:

  • file (String, nil) (defaults to: nil)

    path to the file to write debug data to, or nil to print to STDERR

Returns:

  • self



169
170
171
172
# File 'lib/patron/session.rb', line 169

def enable_debug(file = nil)
  set_debug_file(file.to_s)
  self
end

#escape(value) ⇒ Object Also known as: urlencode

Escapes the provided string using libCURL URL escaping functions.

Parameters:

  • value (String)

    plain string to URL-escape @return [String] the escaped string



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'ext/patron/session_ext.c', line 215

static VALUE session_escape(VALUE self, VALUE value) {
  
  VALUE string = StringValue(value);
  char* escaped = NULL;
  VALUE retval = Qnil;

  struct curl_state* state = curl_easy_init();
  escaped = curl_easy_escape(state->handle,
                             RSTRING_PTR(string),
                             (int) RSTRING_LEN(string));

  retval = rb_str_new2(escaped);
  curl_easy_cleanup(state);
  curl_free(escaped);

  return retval;
}

#get(url, headers = {}) ⇒ Patron::Response

Retrieve the contents of the specified url optionally sending the specified headers. If the +base_url+ varaible is set then it is prepended to the +url+ parameter. Any custom headers are merged with the contents of the +headers+ instance variable. The results are returned in a Response object. Notice: this method doesn't accept any data argument: if you need to send a request body with a GET request, when using ElasticSearch for example, please, use the #request method.

Parameters:

  • url (String)

    the URL to fetch

  • headers (Hash) (defaults to: {})

    the hash of header keys to values

Returns:



185
186
187
# File 'lib/patron/session.rb', line 185

def get(url, headers = {})
  request(:get, url, headers)
end

#get_file(url, filename, headers = {}) ⇒ Patron::Response

Retrieve the contents of the specified +url+ as with #get, but the content at the URL is downloaded directly into the specified file. The file will be accessed by libCURL bypassing the Ruby runtime entirely.

Note that when using this option, the Response object will have ++nil++ as the body, and you will need to read your target file for access to the body string).

Parameters:

  • url (String)

    the URL to fetch

  • filename (String)

    path to the file to save the response body in

Returns:



199
200
201
# File 'lib/patron/session.rb', line 199

def get_file(url, filename, headers = {})
  request(:get, url, headers, :file => filename)
end

#handle_cookies(file_path = nil) ⇒ Object

TODO:

the cookie jar and cookie file path options should be split

Turn on cookie handling for this session, storing them in memory by default or in +file+ if specified. The file must be readable and writable. Calling multiple times will add more files.

Parameters:

  • file_path (String) (defaults to: nil)

    path to an existing cookie jar file, or nil to store cookies in memory

Returns:

  • self



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/patron/session.rb', line 143

def handle_cookies(file_path = nil)
  if file_path
    path = Pathname(file_path).expand_path
    
    if !File.exists?(file_path) && !File.writable?(path.dirname)
      raise ArgumentError, "Can't create file #{path} (permission error)"
    elsif File.exists?(file_path) && !File.writable?(file_path)
      raise ArgumentError, "Can't read or write file #{path} (permission error)"
    end
  else
    path = nil
  end
  
  # Apparently calling this with an empty string sets the cookie file,
  # but calling it with a path to a writable file sets that file to be
  # the cookie jar (new cookies are written there)
  add_cookie_file(path.to_s)
  
  self
end

#handle_request(request) ⇒ Patron::Response

Peform the actual HTTP request by calling libcurl. Each filed in the +request+ object will be used to set the appropriate option on the libcurl library. After the request completes, a Response object will be created and returned.

In the event of an error in the libcurl library, a Ruby exception will be created and raised. The exception will return the libcurl error code and error message.

Parameters:

  • request (Patron::Request)

    the request to use when filling the CURL options

Returns:



727
728
729
730
# File 'ext/patron/session_ext.c', line 727

static VALUE session_handle_request(VALUE self, VALUE request) {
  set_options_from_request(self, request);
  return rb_ensure(&perform_request, self, &cleanup, self);
}

#head(url, headers = {}) ⇒ Patron::Response

Same as #get but performs a HEAD request.

Parameters:

  • url (String)

    the URL to fetch

  • headers (Hash) (defaults to: {})

    the hash of header keys to values

Returns:

See Also:



209
210
211
# File 'lib/patron/session.rb', line 209

def head(url, headers = {})
  request(:head, url, headers)
end

#interruptvoid

This method returns an undefined value.

Interrupt any currently executing request. This will cause the current request to error and raise an exception.



762
763
764
765
766
# File 'ext/patron/session_ext.c', line 762

static VALUE session_interrupt(VALUE self) {
  struct curl_state *state = get_curl_state(self);
  state->interrupt = 1;
  return self;
}

#patch(url, data, headers = {}) ⇒ Patron::Response

TODO:

inconsistency with "post" - Hash not accepted

Uploads the passed data to the specified url using an HTTP PATCH. Note that unline ++post++, a Hash is not accepted as the ++data++ argument.

Parameters:

  • url (String)

    the URL to fetch

  • data (#to_s, #to_path)

    an object that can be converted to a String to create the request body, or that responds to #to_path to upload the entire request body from that file

  • headers (Hash) (defaults to: {})

    the hash of header keys to values

Returns:



249
250
251
# File 'lib/patron/session.rb', line 249

def patch(url, data, headers = {})
  request(:patch, url, headers, :data => data)
end

#post(url, data, headers = {}) ⇒ Patron::Response

Uploads the passed data to the specified url using an HTTP POST.

Parameters:

  • url (String)

    the URL to fetch

  • data (Hash, #to_s, #to_path)

    a Hash of form fields/values, or an object that can be converted to a String to create the request body, or an object that responds to #to_path to upload the entire request body from that file

  • headers (Hash) (defaults to: {})

    the hash of header keys to values

Returns:



273
274
275
276
277
278
279
# File 'lib/patron/session.rb', line 273

def post(url, data, headers = {})
  if data.is_a?(Hash)
    data = data.map {|k,v| urlencode(k.to_s) + '=' + urlencode(v.to_s) }.join('&')
    headers['Content-Type'] = 'application/x-www-form-urlencoded'
  end
  request(:post, url, headers, :data => data)
end

#post_file(url, filename, headers = {}) ⇒ Patron::Response

Uploads the contents of file to the specified url using an HTTP POST. The file will be sent "as-is" without any multipart encoding.

Parameters:

  • url (String)

    the URL to fetch

  • filename (String)

    path to the file to be uploaded

  • headers (Hash) (defaults to: {})

    the hash of header keys to values

Returns:



288
289
290
# File 'lib/patron/session.rb', line 288

def post_file(url, filename, headers = {})
  request(:post, url, headers, :file => filename)
end

#post_multipart(url, data, filename, headers = {}) ⇒ Patron::Response

Uploads the contents of filename to the specified url using an HTTP POST, in combination with given form fields passed in data.

Parameters:

  • url (String)

    the URL to fetch

  • data (Hash)

    hash of the form fields

  • filename (String)

    path to the file to be uploaded

  • headers (Hash) (defaults to: {})

    the hash of header keys to values

Returns:



300
301
302
# File 'lib/patron/session.rb', line 300

def post_multipart(url, data, filename, headers = {})
  request(:post, url, headers, {:data => data, :file => filename, :multipart => true})
end

#put(url, data, headers = {}) ⇒ Patron::Response

TODO:

inconsistency with "post" - Hash not accepted

Uploads the passed data to the specified url using an HTTP PUT. Note that unline ++post++, a Hash is not accepted as the ++data++ argument.

Parameters:

  • url (String)

    the URL to fetch

  • data (#to_s, #to_path)

    an object that can be converted to a String to create the request body, or that responds to #to_path to upload the entire request body from that file

  • headers (Hash) (defaults to: {})

    the hash of header keys to values

Returns:



235
236
237
# File 'lib/patron/session.rb', line 235

def put(url, data, headers = {})
  request(:put, url, headers, :data => data)
end

#put_file(url, filename, headers = {}) ⇒ Patron::Response

Uploads the contents of file to the specified url using an HTTP PUT. The file will be sent "as-is" without any multipart encoding.

Parameters:

  • url (String)

    the URL to fetch

  • filename (String)

    path to the file to be uploaded

  • headers (Hash) (defaults to: {})

    the hash of header keys to values

Returns:



260
261
262
# File 'lib/patron/session.rb', line 260

def put_file(url, filename, headers = {})
  request(:put, url, headers, :file => filename)
end

#request(action, url, headers, options = {}) ⇒ Patron::Response

Send an HTTP request to the specified url.

Parameters:

  • action (#to_s)

    the HTTP verb

  • url (String)

    the URL for the request

  • headers (Hash)

    headers to send along with the request

  • options (Hash) (defaults to: {})

    any additonal setters to call on the Request

Returns:

See Also:



326
327
328
329
# File 'lib/patron/session.rb', line 326

def request(action, url, headers, options = {})
  req = build_request(action, url, headers, options)
  handle_request(req)
end

#resetObject

FIXME: figure out how this method should be used at all given Session is not multithreaded. FIXME: also: what is the difference with interrupt() and also relationship with cleanup()? Reset the underlying cURL session. This effectively closes all open connections and disables debug output. There is no need to call this method manually after performing a request, since cleanup is performed automatically but the method can be used from another thread to abort a request currently in progress.

Returns:

  • self



743
744
745
746
747
748
749
750
751
752
753
754
755
# File 'ext/patron/session_ext.c', line 743

static VALUE session_reset(VALUE self) {
  struct curl_state *state;
  Data_Get_Struct(self, struct curl_state, state);

  if (NULL != state->handle) {
    cleanup(self);
    curl_easy_cleanup(state->handle);
    state->handle = NULL;
    session_close_debug_file(state);
  }

  return self;
}

#response_class#new

Returns the class that will be used to build a Response from a Curl call.

Primarily useful if you need a very lightweight Response object that does not have to perform all the parsing of various headers/status codes. The method must return a module that supports the same interface for +new+ as ++Patron::Response++

Returns:

  • (#new)

    Returns any object that responds to .new with 6 arguments

See Also:



342
343
344
# File 'lib/patron/session.rb', line 342

def response_class
  ::Patron::Response
end

#set_debug_file(file) ⇒ Object

Enable debug output to stderr or to specified +file+.

Parameters:

  • file (String, nil)

    path to the debug file, or nil to write to STDERR @return self



798
799
800
801
802
803
804
805
806
807
808
809
810
811
# File 'ext/patron/session_ext.c', line 798

static VALUE set_debug_file(VALUE self, VALUE file) {
  struct curl_state *state = get_curl_state(self);
  char* file_path = RSTRING_PTR(file);

  session_close_debug_file(state);

  if(file_path != NULL && strlen(file_path) != 0) {
    state->debug_file = open_file(file, "wb");
  } else {
    state->debug_file = stderr;
  }

  return self;
}

#unescape(value) ⇒ Object Also known as: urldecode

Unescapes the provided string using libCURL URL escaping functions.

Parameters:

  • value (String)

    URL-encoded String to unescape @return [String] unescaped (decoded) string



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'ext/patron/session_ext.c', line 239

static VALUE session_unescape(VALUE self, VALUE value) {
  VALUE string = StringValue(value);
  char* unescaped = NULL;
  VALUE retval = Qnil;

  struct curl_state* state = curl_easy_init();
  unescaped = curl_easy_unescape(state->handle,
                                 RSTRING_PTR(string),
                                 (int) RSTRING_LEN(string),
                                 NULL);

  retval = rb_str_new2(unescaped);
  curl_free(unescaped);
  curl_easy_cleanup(state);

  return retval;
}