ether_joe
ether_joe

Reputation: 1108

need to persist cookies in Ruby ala Python's 'requests' library Session() object

So I have a Python script that's working successfully to call a series of URLs with get and post requests, which eventually results in an authentication token I can use for further work. The Python script uses the requests library, and starts things off with a Session object like so:

session = requests.Session()
initial_auth = session.request('GET', login_url)
step_2_url = do_stuff_to_initial_auth()
intermediate_token = session.request('POST', step_2_url)
step_3_url = do_stuff_to_intermediate_token()
final_auth = session.request('GET', step_3_url)

I'm trying to port the script to Ruby, but the script fails at the final step -- the remote service returns some 'Page Expired' html rather than the success page received by the Python script. Digging deeper, I'm seeing that there's a fair amount of cookie state passed from step to step, and that the Python requests.Session object is handling the cookie state automagically behind the scenes.

I'm looking at httparty and rest-client for equivalent magic functionality. I'm seeing references to cookiejars and Resources, but using a cookiejar so far to set cookies isn't working for me.

Is there a way in the Ruby ecosystem to automagically handle cookies across multiple requests like Python's requests.Session?

Thanks ~~

Upvotes: 0

Views: 249

Answers (1)

Mitch
Mitch

Reputation: 546

Try mechanize. For example:

mechanize  = Mechanize.new
page       = mechanize.get(url)
other_page = mechanize.get(other_url)

This persists cookies across requests.

Upvotes: 1

Related Questions