Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- I am trying to take some working code and change from urlib2 to requests. The original code provides basic login information of username, password and posts the KEY and SECRET in the header of the urllib2 request. The following code is my attempt to change to using the requests module and gain some functionality for making additional API calls. I have tried dozens of combinations and all return a code 400. Apparently, my requests code does not successfully furnish the needed information to return a 200 response and provide the needed authorization token.
- ## Import needed modules
- import urllib2, urllib, base64
- import httplib
- import requests
- import json
- ## initialize variables
- KEY = "7f1xxxx-3xxx-4xxx-9a7f-8be66839dede"
- SECRET = "45xxxxxx-45xxx-469a-9ae9-a7927a76cfeb"
- userName = "my-email@xxx.com"
- passWord = "mypassword"
- URL = "https://company.com/auth/token"
- token = None
- sessionid = None
- DATA = urllib.urlencode({"grant_type":"password",
- "username":userName,
- "password":passWord})
- base64string = base64.encodestring('%s:%s' % (KEY, SECRET)).replace('n', '')
- request = urllib2.Request(URL, DATA)
- request.add_header("Authorization", "Basic %s" % base64string)
- result = urllib2.urlopen(request)
- token = result.read()
- print token
- client = requests.session()
- payload = {"grant_type":"password",
- "username":userName,
- "password":passWord,
- "applicationId": KEY
- }
- headers = {'content-type':'application/json',
- "grant_type":"password",
- "username":userName,
- "password":passWord,
- 'applicationsId': KEY,
- 'Authorization': base64string,
- 'token': token,
- 'sessionid': sessionid
- }
- response = client.post(URL, params = payload, headers=headers)
- token = response.content
- print token
- {"error":"invalid_request"}
- print response
- <Response [400]>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement