Search code examples
pythonpython-requeststrello

How to make a Trello session persist using Python as the client?


I'm trying to write a Python script that, from my command line, will allow me to:

  1. Log in to Trello

  2. Use the Trello Python API to retrieve data from Trello boards, etc.

I'm restricted to using Python 2.7.6, so please don't offer any Python 3 suggestions — I won't be able to use them.

I'm able to log in to Trello using the requests module; however, I'm stuck on retrieving a user key in order to be able to use the Trello API.

Here's what I'm doing so far:

import trello
import requests

# Not shown: retrieve username and password from user

sess = requests.Session()

loginData = {
    'method': 'password',
    'factors[user]': username,
    'factors[password]': password
}

TRELLO_LOGIN_URL = "https://trello.com/1/authentication"

resp = sess.post(TRELLO_LOGIN_URL, trelloLogin)     # resp => <Response [200]>

At this point, the resp.text consists of a dictionary (which works equally well in JavaScript or Python) containing a single key code whose value is a very long string of gibberish). I assume this (and the 200 status code in the response object) means that I logged in successfully.

So, now that I'm (presumably) logged in, I request the token URL from the API:

api = trello.TrelloApi(MY_API_KEY)
tokenUrl = api.get_token_url('MyApp') # => https://trello.com/1/authorize?key=<mykey>&name=MyApp&expiration=30days&response_type=token&scope=read,write

But when I try to use that URL:

sess.get(tokenUrl)

the response text I get (consisting of the HTML for an authorization page) has a "Log In" button, rather than the "Approve" button that I see when I do this in my browser. To me, this suggests that the requests.Session object is not persisting properly. Perhaps it's using incorrect cookies or something in the get() request?

Honestly, I'm not all that concerned about the nuts and bolts of what's going wrong, only about what I have to do to fix it. How do I make the session persist into that get() call so I can do the next part?

(Of course, it's entirely possible — even likely — that my approach is incorrect from the ground up, but I haven't been able to find any documentation to tell me what I should be doing differently, so this is the best I could come up with from what I have found. If there are instructions on doing this another way — but still from the command line — feel free to point me to them.)


Solution

  • Apparently there are 2 calls to make to get the token:

    1. https://trello.com/1/authentication which contains the code string in the response
    2. https://trello.com/1/authorization/session use the code retrieved previously to post, should return 204 and then token would be set to cookies. (You will also need to provide a dsc string, for the detail please try inspect the requests via the chrome dev tools.)