Advertisement
Guest User

Example REST Client in Python

a guest
Feb 23rd, 2016
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. # IMPORTS
  4.  
  5. import json
  6. import os
  7.  
  8. from restful_lib import Connection
  9.  
  10. # DECLARES
  11.  
  12. username = 'rest'
  13. password = 'rest'
  14.  
  15. project_name = os.getenv('bamboo_planKey', '').split('-')[0]
  16. short_plan_name = os.getenv('bamboo_shortPlanName', None)
  17. plan_repository_branch = os.getenv('bamboo_planRepository_branchName', None)
  18. base_url = 'http://www.example.com:8080/rest/api/latest'
  19.  
  20. if project_name == '' or short_plan_name == None:
  21.   raise ValueError('There appears to be a problem with the Environment Variables.')
  22.  
  23. if plan_repository_branch == 'dev':
  24.   exit()
  25.  
  26. rest_path = 'plan/{0}-GATHER/branch/{1}'.format(project_name,short_plan_name)
  27.  
  28. headers = {'content-type' : 'application/json', 'accept' : 'application/json'}
  29. args = {'os_authType' : 'basic'}
  30.  
  31. # SUBS
  32.  
  33. def parse_response(resp):
  34.   status = int(resp[u'headers']['status'])
  35.   message = None
  36.   if u'body' in resp:
  37.     try:
  38.       resp_json = json.loads(resp[u'body'])
  39.       print resp_json
  40.       if u'message' in resp_json:
  41.         message = resp_json[u'message']
  42.     except ValueError:
  43.       message = resp[u'body']
  44.   return status,message
  45.  
  46. # DO STUFF
  47. conn = Connection(base_url,username,password)
  48.  
  49. resp = conn.request_get(rest_path, headers=headers, args=args)
  50.  
  51. status,message = parse_response(resp)
  52.  
  53.  
  54. # If status is 204, it means NO CONTENT, as in, that Plan Branch doesn't exist yet
  55. # So we create it now
  56. if status == 204:
  57.   args['enabled'] = 'true'
  58.   resp = conn.request_put(rest_path, headers=headers, args=args)
  59.  
  60.   status,message = parse_response(resp)
  61.  
  62. # If at this point status is anything but 200, there was an error, fail the build.
  63. if status != 200:
  64.   raise Exception(status, message)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement