Advertisement
Guest User

Untitled

a guest
Mar 3rd, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. 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.
  2.  
  3.  
  4. ## Import needed modules
  5.  
  6. import urllib2, urllib, base64
  7. import httplib
  8. import requests
  9. import json
  10.  
  11. ## initialize variables
  12.  
  13. KEY = "7f1xxxx-3xxx-4xxx-9a7f-8be66839dede"
  14. SECRET = "45xxxxxx-45xxx-469a-9ae9-a7927a76cfeb"
  15. userName = "my-email@xxx.com"
  16. passWord = "mypassword"
  17. URL = "https://company.com/auth/token"
  18. token = None
  19. sessionid = None
  20.  
  21.  
  22. DATA = urllib.urlencode({"grant_type":"password",
  23. "username":userName,
  24. "password":passWord})
  25.  
  26. base64string = base64.encodestring('%s:%s' % (KEY, SECRET)).replace('n', '')
  27. request = urllib2.Request(URL, DATA)
  28. request.add_header("Authorization", "Basic %s" % base64string)
  29. result = urllib2.urlopen(request)
  30. token = result.read()
  31. print token
  32.  
  33. client = requests.session()
  34.  
  35. payload = {"grant_type":"password",
  36. "username":userName,
  37. "password":passWord,
  38. "applicationId": KEY
  39. }
  40.  
  41. headers = {'content-type':'application/json',
  42. "grant_type":"password",
  43. "username":userName,
  44. "password":passWord,
  45. 'applicationsId': KEY,
  46. 'Authorization': base64string,
  47. 'token': token,
  48. 'sessionid': sessionid
  49. }
  50.  
  51. response = client.post(URL, params = payload, headers=headers)
  52. token = response.content
  53. print token
  54. {"error":"invalid_request"}
  55.  
  56. print response
  57. <Response [400]>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement