def testUpdateByUserForOthers(self): """fail to update alarms belonging to others""" # TODO: improve test to attempt to update alarm belonging to another user instead of a higher level user path = "/resources/alarms/100" # id taken from DB (belongs to a power user) user = self.testuser res = Resource(self.baseurl, filters=[user]) try: exception = False # perform request output = res.request("PUT", path=path, params_dict = {"alarm_type_id": 14, # changeing from 2 to 1 "account_id": 106, # std user from the DB "sensor_type_id": 100, # value from DB "greater_than_p": True, "value": 100 } ) except Unauthorized: exception = True # check that update failed self.assertTrue(exception, "User was able to update alarm for another user.")
def testNew(self): """succeed in creating fill""" path = "/resources/data/fills" user = self.testfilluser res = Resource(self.baseurl, filters=[user]) # perform request output = res.request("POST", path=path, params_dict={ "fill_number": 100, "air_begin_datetime": "010110080910", "end_datetime": "110110080910", "start_datetime": "010110080910", "rotation_number": 100, "bin_id": 14, "hybrid_code": "100A", "field_code": "100A", "storage_bin_number": 100, "storage_bin_code": "100A", "pre_mc_count": 2, "pre_mc": "33,31.2", "post_mc_count": 3, "post_mc": "17,16,17.2", "bushels": 42 }) self.unauthorizedChecks([None, self.testuser], path, method="POST")
class Query(object): def __init__(self, url=GITHUB_URL, params=None, payload=None, headers=None, filters=None, access_token=None): self.url = url self.params = params or dict() self.payload = payload or dict() self.headers = headers or {'Content-Type': 'application/json'} filters = filters or list() self.resource = Resource( url, pool=ConnectionPool(factory=Connection), filters=filters, ) if access_token is not None: self.params["access_token"] = access_token def concat_path(self, *args): for path in args: self.resource.update_uri(path) def do_GET(self, path=None, params=None): params = params or self.params response = self.resource.get(path, self.headers, params) return self.parse_response(response.body_string()) def do_POST(self, path=None, payload=None, params=None): payload = payload or self.payload params = params or self.params response = self.resource.post(path, json.dumps(payload), self.headers, params) return self.parse_response(response.body_string()) def do_DELETE(self, path=None, params=None): params = params or self.params response = self.resource.delete(path, self.headers, params) return self.parse_response(response.body_string()) def do_PATCH(self, path=None, payload=None, params=None): payload = payload or self.payload params = params or self.params response = self.resource.request("PATCH", path, json.dumps(payload), self.headers, params) return self.parse_response(response.body_string()) def parse_response(self, response): try: return json.loads(response) except: return response def __repr__(self): return "uri:<{0}>".format(self.resource.uri) def __str__(self): return self.resource.uri
def rest_call(url, method, data, headers, client_auth_key, client_auth_secret): consumer = oauth2.Consumer(key=client_auth_key, secret=client_auth_secret) auth = OAuthFilter('*',consumer) resource = Resource(url, filters=[auth]) response = resource.request(method, payload=data, headers=headers, params=None) json_string = response.body_string() status = response.status return status, json_string
def testAccountsNewDelete(self): path = "/resources/accounts" user = self.testpoweruser res = Resource(self.baseurl, filters=[user]) email = "*****@*****.**" self.assertEqual(None, util.getAccountByEmail(email), "Account to add already exists.") params = { "name": "New User Test", "email": "*****@*****.**", "phone": "15555555555", "privilege_id": 100 } output = res.request("POST", path=path, params_dict=params) self.assertEqual(200, output.status_int, "Wrong response code from post.") xlink = json.loads(output.body_string()) #check account got created. new_account = util.getAccountByEmail(email) self.assertNotEqual(None, new_account, "New account was not created") #Check link returned is correct. path = xlink["xlink"][0] self.assertEquals("/resources/accounts/" + str(new_account.id), path, "Link returned does not match new account") #DELETE new account output = res.request("DELETE", path=path) self.assertEqual(204, output.status_int, "Wrong response code from delete.") new_account = util.getAccountByEmail(email) self.assertEqual(None, util.getAccountByEmail(email), "Failed to delete account.") #authorized checks #new self.unauthorizedChecks( [None, self.testuser, self.testfilluser, self.testconfiguser], "/resources/accounts", "POST", params_dict=params) #delete self.unauthorizedChecks( [None, self.testuser, self.testfilluser, self.testconfiguser], "/resources/accounts/1", "DELETE")
def newDevice(self): path = "/resources/conf/devices" user = self.testconfiguser res = Resource(self.baseurl, filters=[user]) output = res.request("POST", path, params_dict=self.newparams) self.assertEqual(200, output.status_int, "Wrong response code from post.") xlink = json.loads(output.body_string()) return xlink
def testDeleteByPowerUser(self): """Power user to succeed in deleting alarm""" path = "/resources/alarms/113" # alarm belonging to a poweruser user = self.testpoweruser res = Resource(self.baseurl, filters=[user]) output = res.request("DELETE",path=path) self.assertEqual(204,output.status_int,"Power user was unable to delete alarm")
def testDeleteByPowerUserForOthers(self): """succeed in deleting other's alarm contact""" path = "/resources/alarms/112" # alarm contact belonging to another user user = self.testpoweruser res = Resource(self.baseurl, filters=[user]) output = res.request("DELETE",path=path) self.assertEqual(204,output.status_int, "Power user was unable to delete alarm belonging to lower level user.")
def doGithub(url, method="GET", payload=None): # screw it global headers, pool resource = Resource(url, pool=pool) if payload: payload = json.dumps(payload) response = resource.request(headers=headers, payload=payload, method=method) return json.loads(response.body_string())
def testDeleteByUserForSelf(self): """succeed in deleting own alarm contact""" path = "/resources/alarms/104" # alarm contact belonging to this user user = self.testuser res = Resource(self.baseurl, filters=[user]) output = res.request("DELETE",path=path) self.assertEqual(204,output.status_int, "User was unable to delete alarm belonging to self.")
def rest_call(url, method, data, headers, client_auth_key, client_auth_secret): consumer = oauth2.Consumer(key=client_auth_key, secret=client_auth_secret) auth = OAuthFilter('*', consumer) resource = Resource(url, filters=[auth]) response = resource.request(method, payload=data, headers=headers, params=None) json_string = response.body_string() status = response.status return status, json_string
def testDelete(self): """Succeed in deleting fill.""" path = "/resources/data/fills/100" user = self.testpoweruser res = Resource(self.baseurl, filters=[user]) output = res.request("DELETE", path=path) self.assertEqual(204, output.status_int, "Fill user was unable to delete fill.")
def doGithub( url, method = 'GET', payload = None ): # screw it global headers, pool, serverurl url = serverurl + url resource = Resource(url, pool=pool) if payload: payload = json.dumps(payload) print "getting %s" % url response = resource.request(headers = headers, payload = payload, method = method) return json.loads(response.body_string())
def testGeneralUpdate(self): path = "/resources/conf/general" for user in [self.testconfiguser, self.testpoweruser, self.testsuperuser]: newinterval = random.randrange(300, 600) general = self.getJSONResource(path, user) general['interval'] = newinterval res = Resource(self.baseurl, filters=[user]) output = res.request("PUT", path=path, params_dict=general) self.assertEqual(204, output.status_int, "Wrong response code: " + user.credentials[0]) general = self.getJSONResource(path, user) self.assertEquals(newinterval, int(general['interval']), "General not updated.") self.unauthorizedChecks([None, self.testuser, self.testfilluser], path, method="PUT")
def unauthorizedChecks(self, users, path, method="GET", params_dict=None): """:param users: list of BasicAuths to try, expecting Unauthorized""" for user in users: name = "None" if (user): name = user.credentials[0] exception = False try: res = Resource(self.baseurl, filters=[user]) output = res.request(method, path, params_dict=params_dict) except Unauthorized: exception = True self.assertTrue(exception, "No unauthorized exception for " + name)
def testNewByUserForSelf(self): """create alarm contact for self""" path = "/resources/alarms" user = self.testuser res = Resource(self.baseurl, filters=[user]) # perform request output = res.request("POST",path=path, params_dict = {"alarm_type_id": 10, "account_id":104, "alarm_contact_type_ids": 100}) # check if addition failed self.assertEqual(200, output.status_int, "User was unable to add alarm contact for self.") # get the returned url xlink = json.loads(output.body_string())
def testDeleteNonExistantAlarm(self): """Power user to fail in deleting non-existant alarm""" path = "/resources/alarms/8" user = self.testpoweruser res = Resource(self.baseurl, filters=[user]) try: exception = False output = res.request("DELETE",path=path) except: # which exception should I catch? exception = True self.assertTrue(exception,"Failed to return 404 for missing alarm.")
def testUpdateByUserForSelf(self): """succeed in updating alarm belonging to self""" path = "/resources/alarms/115" # id taken from DB user = self.testuser res = Resource(self.baseurl, filters=[user]) # perform request output = res.request("PUT",path=path, params_dict = {"alarm_type_id": 14, # changeing from 2 to 1 "account_id": 104, # std user from the DB "greater_than_p": True, "value": 105}) # check that update succeeded self.assertEqual(202, output.status_int, "User was unable to update alarm for self.")
def testDeleteByUserForOthers(self): """fail to delete other's alarm contact""" path = "/resources/alarms/alarm_contacts/100" # alarm belonging to a poweruser user = self.testuser res = Resource(self.baseurl, filters=[user]) try: exception = False output = res.request("DELETE",path=path) except: # which exception should I catch? exception = True self.assertTrue(exception,"Failed to return 404 for missing alarm.")
def testGet(self): """Test ability to get list of alarm events""" path = "/resources/alarms/events" for user in [self.testuser, self.testpoweruser, self.testsuperuser]: # perform request res = Resource(self.baseurl, filters=[user]) output = res.request("GET",path=path, params_dict = {"begin": "010111134553", "end": "120111134553"}) self.assertEqual(200,output.status_int, "User, " + str(user) + " was unable to obtain list of alarm events.") self.unauthorizedChecks([None], path)
def testGet(self): """Test ability to get list of fills""" path = "/resources/data/fills" for user in [self.testuser, self.testpoweruser, self.testsuperuser]: res = Resource(self.baseurl, filters=[user]) # test with all of the parameters present output = res.request("GET", path=path, params_dict={ "bin_id": 100, "field_code": "100A", "hybrid_code": "100A", "storage_bin_number": 100, "storage_bin_code": "100A", "begin_datetime": "010110080910", "end_datetime": "120111080910" }) try: exception_p = False output = res.request("GET", path=path, params_dict={ "bin_id": 100, "field_code": "100A", "hybrid_code": "100A", "storage_bin_number": 100, "storage_bin_code": "100A", "begin_datetime": "010111080910", "end_datetime": "120111080910" }) except: exception_p = True self.assertFalse(exception_p, "Wrongfully, matching fills were found.") self.unauthorizedChecks([None], path)
def testGetReadingData(self): """Test ability to get data associated with a given reading.""" path = "/resources/data/readings/100" for user in [self.testuser, self.testpoweruser, self.testsuperuser]: res = Resource(self.baseurl, filters=[user]) output = res.request("GET", path=path, params_dict={ "bin_id": 102, "bin_section_id": 103, "sensor_type_id": 10 }) self.unauthorizedChecks([None], path)
def testSensorsGetUpdate(self): xlink = self.newSensor() id = self.getFirstIdFromXLink(xlink) self.convert_py = "8 + 20" self.newparams['convert_py'] = self.convert_py path = "/resources/conf/sensors/" + str(id) for user in [self.testconfiguser, self.testpoweruser, self.testsuperuser]: self.convert_py = "5 +" + str(random.randrange(100, 999)) self.newparams['convert_py'] = self.convert_py res = Resource(self.baseurl, filters=[user]) output = res.request("PUT", path=path, params_dict=self.newparams) self.assertEqual(204, output.status_int, "Wrong response code: " + user.credentials[0]) sensor = self.getSensor(id) self.assertEqual(self.convert_py, sensor['convert_py'], 'Sensor was not updated.') self.unauthorizedChecks([None, self.testuser, self.testfilluser], path, method='PUT', params_dict=self.newparams) self.unauthorizedChecks([None], path, method='GET') self.deleteSensor(id)
def testDevicesGetUpdate(self): xlink = self.newDevice() id = self.getFirstIdFromXLink(xlink) self.name = "updated device" self.newparams['name'] = self.name path = "/resources/conf/devices/" + str(id) for user in [self.testconfiguser, self.testpoweruser, self.testsuperuser]: self.name = "test device" + str(random.randrange(100, 999)) self.newparams['name'] = self.name res = Resource(self.baseurl, filters=[user]) output = res.request("PUT", path=path, params_dict=self.newparams) self.assertEqual(204, output.status_int, "Wrong response code: " + user.credentials[0]) device = self.getDevice(id) self.assertEqual(self.name, device['name'], 'Device was not updated.') self.unauthorizedChecks([None, self.testuser, self.testfilluser], path, method='PUT', params_dict=self.newparams) self.unauthorizedChecks([None], path, method='GET') self.deleteDevice(id)
def testUpdateByPowerUser(self): """succeed in updating any alarm""" path = "/resources/alarms/101" # alarm id from DB user = self.testpoweruser res = Resource(self.baseurl, filters=[user]) # perform request output = res.request("PUT", path=path, params_dict = {"alarm_type_id": 13, # changeing from 2 to 1 "account_id": 100, # std user from the DB "sensor_type_id": 100, # value from DB "greater_than_p": True, "value": 1000 } ) # check that update succeeded self.assertEqual(202, output.status_int, "Power user was unable to update alarm for another user.")
def testNewByPowerUser(self): """succeed in creating alarm for any user""" path = "/resources/alarms" user = self.testpoweruser res = Resource(self.baseurl, filters=[user]) exception = False # perform request try: output = res.request("POST",path=path, params_dict = {"alarm_type_id": 10, "account_id": 103, "greater_than_p": False, "value": 0}) except Unauthorized: exception = True # check that addition succeeded self.assertFalse(exception, "Power user was unable to add alarm for lower level user.") # get the returned url xlink = json.loads(output.body_string())
def testNewByUserForSelf(self): """succeed in creating alarm for self""" path = "/resources/alarms" user = self.testuser res = Resource(self.baseurl, filters=[user]) # perform request output = res.request("POST", path=path, params_dict = {"alarm_type_id": 10, # value from DB "account_id": 104, # value from DB "sensor_type_id": 100, # value from DB "greater_than_p": True, "value": 100 } ) # check that addition succeeded self.assertEqual(200, output.status_int, "User was unable to add alarm for self.") # get the returned url xlink = json.loads(output.body_string())
def testNewByUserForOthers(self): """create alarm contact for another user""" path = "/resources/alarms/alarm_contacts" user = self.testuser res = Resource(self.baseurl, filters=[user]) try: exception_p = False # perform request output = res.request("POST", path=path, params_dict = {"alarm_id": 1, # value from DB "contact_type_id": 1, # value from DB } ) except: exception_p = True # check that addition failed self.assertTrue(exception_p, "User was able to add alarm contact for another user.")
def testNewByUserForOthers(self): """fail to create alarm for others""" path = "/resources/alarms" user = self.testuser res = Resource(self.baseurl, filters=[user]) # perform request exception = False try: output = res.request("POST", path=path, params_dict = {"alarm_type_id": 10, # value from DB "account_id": 101, # a differnt user from DB "greater_than_p": False, "value": 0 } ) except Unauthorized: exception = True # check that addition failed self.assertTrue(exception, "User was able to add alarm for another user.")
def testAccountsUpdate(self): path = "/resources/accounts/" + str(self.dbfilluser.id) for user in [ self.testfilluser, self.testpoweruser, self.testsuperuser ]: name = user.credentials[0] res = Resource(self.baseurl, filters=[user]) phone = str(random.randrange(10000000000, 99999999999)) params = { "name": self.dbfilluser.name, "email": self.dbfilluser.email, "phone": phone, "privilege_id": self.dbfilluser.privilege_id } output = res.request("PUT", path=path, params_dict=params) self.assertEqual(204, output.status_int, "Wrong response code: " + name) self.dbfilluser = util.getAccountByEmail(self.dbfilluser.email) self.assertEqual(self.dbfilluser.phone, phone, "Account not updated.") self.unauthorizedChecks([None, self.testuser, self.testconfiguser], path, method='PUT', params_dict=params)
def request(self, method, path=None, payload=None, headers=None, **params): """ Perform HTTP call to the couchdb server and manage JSON conversions, support GET, POST, PUT and DELETE. Usage example, get infos of a couchdb server on http://127.0.0.1:5984 : import couchdbkit.CouchdbResource resource = couchdbkit.CouchdbResource() infos = resource.request('GET') @param method: str, the HTTP action to be performed: 'GET', 'HEAD', 'POST', 'PUT', or 'DELETE' @param path: str or list, path to add to the uri @param data: str or string or any object that could be converted to JSON. @param headers: dict, optional headers that will be added to HTTP request. @param raw: boolean, response return a Response object @param params: Optional parameterss added to the request. Parameterss are for example the parameters for a view. See `CouchDB View API reference <http://wiki.apache.org/couchdb/HTTP_view_API>`_ for example. @return: tuple (data, resp), where resp is an `httplib2.Response` object and data a python object (often a dict). """ headers = headers or {} headers.setdefault('Accept', 'application/json') headers.setdefault('User-Agent', USER_AGENT) try: return Resource.request(self, method, path=path, payload=payload, headers=headers, **params) except ResourceError, e: msg = getattr(e, 'msg', '') if e.response and msg: if e.response.headers.get('content-type') == 'application/json': try: msg = json.loads(str(msg)) except ValueError: pass if type(msg) is dict: error = msg.get('reason') else: error = msg if e.status_int == 404: raise ResourceNotFound(error, http_code=404, response=e.response) elif e.status_int == 409: raise ResourceConflict(error, http_code=409, response=e.response) elif e.status_int == 412: raise PreconditionFailed(error, http_code=412, response=e.response) elif e.status_int in (401, 403): raise Unauthorized(e) else: raise RequestFailed(str(e))
def request(self, method, path=None, payload=None, headers=None, **params): """ Perform HTTP call to the couchdb server and manage JSON conversions, support GET, POST, PUT and DELETE. Usage example, get infos of a couchdb server on http://127.0.0.1:5984 : import couchdbkit.CouchdbResource resource = couchdbkit.CouchdbResource() infos = resource.request('GET') @param method: str, the HTTP action to be performed: 'GET', 'HEAD', 'POST', 'PUT', or 'DELETE' @param path: str or list, path to add to the uri @param data: str or string or any object that could be converted to JSON. @param headers: dict, optional headers that will be added to HTTP request. @param raw: boolean, response return a Response object @param params: Optional parameterss added to the request. Parameterss are for example the parameters for a view. See `CouchDB View API reference <http://wiki.apache.org/couchdb/HTTP_view_API>`_ for example. @return: tuple (data, resp), where resp is an `httplib2.Response` object and data a python object (often a dict). """ headers = headers or {} headers.setdefault('Accept', 'application/json') headers.setdefault('User-Agent', USER_AGENT) if payload is not None: #TODO: handle case we want to put in payload json file. if not hasattr(payload, 'read') and not isinstance( payload, basestring): payload = json.dumps(payload).encode('utf-8') headers.setdefault('Content-Type', 'application/json') params = encode_params(params) try: resp = Resource.request(self, method, path=path, payload=payload, headers=headers, **params) except ResourceError, e: msg = getattr(e, 'msg', '') if e.response and msg: if e.response.headers.get( 'content-type') == 'application/json': try: msg = json.loads(msg) except ValueError: pass if type(msg) is dict: error = msg.get('reason') else: error = msg if e.status_int == 404: raise ResourceNotFound(error, http_code=404, response=e.response) elif e.status_int == 409: raise ResourceConflict(error, http_code=409, response=e.response) elif e.status_int == 412: raise PreconditionFailed(error, http_code=412, response=e.response) else: raise
def request(self, method, path=None, payload=None, headers=None, **params): """ Perform HTTP call to the couchdb server and manage JSON conversions, support GET, POST, PUT and DELETE. Usage example, get infos of a couchdb server on http://127.0.0.1:5984 : import couchdbkit.CouchdbResource resource = couchdbkit.CouchdbResource() infos = resource.request('GET') @param method: str, the HTTP action to be performed: 'GET', 'HEAD', 'POST', 'PUT', or 'DELETE' @param path: str or list, path to add to the uri @param data: str or string or any object that could be converted to JSON. @param headers: dict, optional headers that will be added to HTTP request. @param raw: boolean, response return a Response object @param params: Optional parameterss added to the request. Parameterss are for example the parameters for a view. See `CouchDB View API reference <http://wiki.apache.org/couchdb/HTTP_view_API>`_ for example. @return: tuple (data, resp), where resp is an `httplib2.Response` object and data a python object (often a dict). """ headers = headers or {} headers.setdefault("Accept", "application/json") headers.setdefault("User-Agent", USER_AGENT) if payload is not None: # TODO: handle case we want to put in payload json file. if not hasattr(payload, "read") and not isinstance(payload, basestring): payload = json.dumps(payload).encode("utf-8") headers.setdefault("Content-Type", "application/json") params = encode_params(params) try: resp = Resource.request(self, method, path=path, payload=payload, headers=headers, **params) except ResourceError, e: msg = getattr(e, "msg", "") if e.response and msg: if e.response.headers.get("content-type") == "application/json": try: msg = json.loads(msg) except ValueError: pass if type(msg) is dict: error = msg.get("reason") else: error = msg if e.status_int == 404: raise ResourceNotFound(error, http_code=404, response=e.response) elif e.status_int == 409: raise ResourceConflict(error, http_code=409, response=e.response) elif e.status_int == 412: raise PreconditionFailed(error, http_code=412, response=e.response) else: raise
class Query(object): def __init__(self, url=GITHUB_URL, params=None, payload=None, headers=None, filters=None, access_token=None): self.url = url self.params = params or dict() self.payload = payload or dict() self.headers = headers or {'Content-Type':'application/json'} filters = filters or list() self.resource = Resource( url, pool=ConnectionPool(factory=Connection), filters=filters, ) if access_token is not None: self.params["access_token"] = access_token def concat_path(self, *args): for path in args: self.resource.update_uri(path) def do_GET(self, path=None, params=None): params = params or self.params response = self.resource.get( path, self.headers, params) return self.parse_response(response.body_string()) def do_POST(self, path=None, payload=None, params=None): payload = payload or self.payload params = params or self.params response = self.resource.post( path, json.dumps(payload), self.headers, params) return self.parse_response(response.body_string()) def do_DELETE(self, path=None, params=None): params = params or self.params response = self.resource.delete( path, self.headers, params) return self.parse_response(response.body_string()) def do_PATCH(self, path=None, payload=None, params=None): payload = payload or self.payload params = params or self.params response = self.resource.request( "PATCH", path, json.dumps(payload), self.headers, params) return self.parse_response(response.body_string()) def parse_response(self, response): try: return json.loads(response) except: return response def __repr__(self): return u"uri:<{0}>".format(self.resource.uri) def __str__(self): return self.resource.uri
def save_base(self, raw=False, cls=None, origin=None, force_insert=False, force_update=False, using=None, update_fields=None): """ Does the heavy-lifting involved in saving. Subclasses shouldn't need to override this method. It's separate from save() in order to hide the need for overrides of save() to pass around internal-only parameters ('raw', 'cls', and 'origin'). """ assert not (force_insert and force_update) record_exists = False if cls is None: cls = self.__class__ meta = cls._meta if not meta.proxy: origin = cls else: meta = cls._meta if origin and not getattr(meta, "auto_created", False): signals.pre_save.send(sender=origin, instance=self, raw=raw) model_name = str(meta) # If we are in a raw save, save the object exactly as presented. # That means that we don't try to be smart about saving attributes # that might have come from the parent class - we just save the # attributes we have been given to the class we have been given. # We also go through this process to defer the save of proxy objects # to their actual underlying model. if not raw or meta.proxy: if meta.proxy: org = cls else: org = None for parent, field in meta.parents.items(): # At this point, parent's primary key field may be unknown # (for example, from administration form which doesn't fill # this field). If so, fill it. if field and getattr(self, parent._meta.pk.attname) is None and getattr(self, field.attname) is not None: setattr(self, parent._meta.pk.attname, getattr(self, field.attname)) self.save_base(cls=parent, origin=org, using=using) if field: setattr(self, field.attname, self._get_pk_val(parent._meta)) if meta.proxy: return if not meta.proxy: pk_val = self._get_pk_val(meta) pk_is_set = pk_val is not None get_args = {} get_args[ROA_ARGS_NAMES_MAPPING.get('FORMAT', 'format')] = ROA_FORMAT get_args.update(ROA_CUSTOM_ARGS) # Construct Json payload serializer = self.get_serializer(self) payload = self.get_renderer().render(serializer.data) payload = model_to_dict(self) # Add serializer content_type headers = get_roa_headers() headers.update(self.get_serializer_content_type()) # check if resource use custom primary key if not meta.pk.attname in ['pk', 'id']: # consider it might be inserting so check it first # @todo: try to improve this block to check if custom pripary key is not None first resource = Resource(self.get_resource_url_detail(), filters=ROA_FILTERS, **ROA_SSL_ARGS) try: response = resource.get(payload=None, headers=headers, **get_args) except ResourceNotFound: # since such resource does not exist, it's actually creating pk_is_set = False except RequestFailed: pk_is_set = False if force_update or pk_is_set and not self.pk is None: record_exists = True resource = Resource(self.get_resource_url_detail(), filters=ROA_FILTERS, **ROA_SSL_ARGS) try: logger.debug(u"""Modifying : "%s" through %s with payload "%s" and GET args "%s" """ % ( force_unicode(self), force_unicode(resource.uri), force_unicode(payload), force_unicode(get_args))) response = resource.request('patch', payload=payload, headers=headers, **get_args) except RequestFailed as e: raise ROAException(e) else: record_exists = False resource = Resource(self.get_resource_url_list(), filters=ROA_FILTERS, **ROA_SSL_ARGS) try: logger.debug(u"""Creating : "%s" through %s with payload "%s" and GET args "%s" """ % ( force_unicode(self), force_unicode(resource.uri), force_unicode(payload), force_unicode(get_args))) response = resource.post(payload=payload, headers=headers, **get_args) except RequestFailed as e: raise ROAException(e) response = force_unicode(response.body_string()).encode(DEFAULT_CHARSET) data = self.get_parser().parse(StringIO(response)) serializer = self.get_serializer(data=data) if not serializer.is_valid(): raise ROAException(u'Invalid deserialization for %s model: %s' % (self, serializer.errors)) # try: # self.pk = int(serializer.object.pk) # except ValueError: # self.pk = serializer.object.pk for key in serializer.data.keys(): setattr(self, key, serializer.data[key]) # self = serializer.data if origin: signals.post_save.send(sender=origin, instance=self, created=(not record_exists), raw=raw)
def request(self, method, path=None, payload=None, headers=None, params_dict=None, **params): """ Perform HTTP call to the couchdb server and manage JSON conversions, support GET, POST, PUT and DELETE. Usage example, get infos of a couchdb server on http://127.0.0.1:5984 : import couchdbkit.CouchdbResource resource = couchdbkit.CouchdbResource() infos = resource.request('GET') @param method: str, the HTTP action to be performed: 'GET', 'HEAD', 'POST', 'PUT', or 'DELETE' @param path: str or list, path to add to the uri @param data: str or string or any object that could be converted to JSON. @param headers: dict, optional headers that will be added to HTTP request. @param raw: boolean, response return a Response object @param params: Optional parameterss added to the request. Parameterss are for example the parameters for a view. See `CouchDB View API reference <http://wiki.apache.org/couchdb/HTTP_view_API>`_ for example. @return: tuple (data, resp), where resp is an `httplib2.Response` object and data a python object (often a dict). """ headers = headers or {} headers.setdefault('Accept', 'application/json') headers.setdefault('User-Agent', USER_AGENT) logger.debug("Resource uri: %s" % self.initial['uri']) logger.debug("Request: %s %s" % (method, path)) logger.debug("Headers: %s" % str(headers)) logger.debug("Params: %s" % str(params)) try: return Resource.request(self, method, path=path, payload=payload, headers=headers, **params) except ResourceError, e: msg = getattr(e, 'msg', '') if e.response and msg: if e.response.headers.get('content-type') == \ 'application/json': try: msg = json.loads(str(msg)) except ValueError: pass if type(msg) is dict: error = msg.get('reason') else: error = msg if e.status_int == 404: raise ResourceNotFound(error, http_code=404, response=e.response) elif e.status_int == 409: raise ResourceConflict(error, http_code=409, response=e.response) elif e.status_int == 412: raise PreconditionFailed(error, http_code=412, response=e.response) elif e.status_int in (401, 403): raise Unauthorized(e) else: raise RequestFailed(str(e))
def deleteDevice(self, id): path = "/resources/conf/devices/" + str(id) user = self.testconfiguser res = Resource(self.baseurl, filters=[user]) output = res.request("DELETE", path=path) self.assertEqual(204, output.status_int, "Wrong response code from delete.")
payload=json.dumps(authreqdata)) token = json.loads(response.body_string())['token'] #Once you have a token, you can pass that in the Authorization header #You can store this in a cache and throw away the user/password #This is just an example query. See http://developer.github.com/v3/ #for more about the url structure resource = Resource('https://api.github.com/repos/%s/labels' % repo, pool=pool) headers = {'Content-Type' : 'application/json' } headers['Authorization'] = 'token %s' % token response = resource.get(headers = headers) labels = json.loads(response.body_string()) label_names = [n['name'] for n in labels] for name in label_names: if name.startswith('Link <=> '): print "Updating Link %s" % name payload = {"name": name, "color": color_cycle.next() } print payload headers = {'Content-Type' : 'application/json' } headers['Authorization'] = 'token %s' % token resource = Resource('https://api.github.com/repos/%s/labels/%s' % (repo, name), pool=pool) response = resource.request('PATCH', payload=json.dumps(payload), headers=headers)