Python requests.put() Examples

The following are 30 code examples for showing how to use requests.put(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module requests , or try the search function .

Example 1
Project: hsds   Author: HDFGroup   File: helper.py    License: Apache License 2.0 8 votes vote down vote up
def setupDomain(domain, folder=False):
    endpoint = config.get("hsds_endpoint")
    headers = getRequestHeaders(domain=domain)
    req = endpoint + "/"
    rsp = requests.get(req, headers=headers)
    if rsp.status_code == 200:
        return  # already have domain
    if rsp.status_code != 404:
        # something other than "not found"
        raise ValueError(f"Unexpected get domain error: {rsp.status_code}")
    parent_domain = getParentDomain(domain)
    if parent_domain is None:
        raise ValueError(f"Invalid parent domain: {domain}")
    # create parent domain if needed
    setupDomain(parent_domain, folder=True)

    headers = getRequestHeaders(domain=domain)
    body=None
    if folder:
        body = {"folder": True}
        rsp = requests.put(req, data=json.dumps(body), headers=headers)
    else:
        rsp = requests.put(req, headers=headers)
    if rsp.status_code != 201:
        raise ValueError(f"Unexpected put domain error: {rsp.status_code}") 
Example 2
Project: pyfirebase   Author: afropolymath   File: firebase.py    License: MIT License 6 votes vote down vote up
def run(self):
        try:
            self.sse = ClosableSSEClient(self.url)
            for msg in self.sse:
                event = msg.event
                if event is not None and event in ('put', 'patch'):
                    response = json.loads(msg.data)
                    if response is not None:
                        # Default to CHILD_CHANGED event
                        occurred_event = FirebaseEvents.CHILD_CHANGED
                        if response['data'] is None:
                            occurred_event = FirebaseEvents.CHILD_DELETED

                        # Get the event I'm trying to listen to
                        ev = FirebaseEvents.id(self.event_name)
                        if occurred_event == ev or ev == FirebaseEvents.CHILD_CHANGED:
                            self.callback(event, response)
        except socket.error:
            pass 
Example 3
Project: unicorn-binance-websocket-api   Author: oliver-zehentleitner   File: unicorn_binance_websocket_api_restclient.py    License: MIT License 6 votes vote down vote up
def keepalive_listen_key(self, listen_key):
        """
        Ping a listenkey to keep it alive

        :param listen_key: the listenkey you want to keepalive
        :type listen_key: str

        :return: the response
        :rtype: str or False
        """
        logging.debug("BinanceWebSocketApiRestclient->keepalive_listen_key(" + str(listen_key) + ")")
        method = "put"
        try:
            return self._request(method, self.path_userdata, False, {'listenKey': str(listen_key)})
        except KeyError:
            return False
        except TypeError:
            return False 
Example 4
Project: aws-ops-automator   Author: awslabs   File: custom_resource.py    License: Apache License 2.0 6 votes vote down vote up
def _send_response(self):
        """
        Send the response to cloudformation provided url
        :return:
        """
        # Build the PUT request and the response data
        resp = json.dumps(self.response)

        headers = {
            'content-type': '',
            'content-length': str(len(resp))
        }

        # PUT request to cloudformation provided S3 url
        try:
            response = requests.put(self.response_url, data=json.dumps(self.response), headers=headers)
            response.raise_for_status()
            return {"status_code: {}".format(response.status_code),
                    "status_message: {}".format(response.text)}
        except Exception as exc:
            raise_exception(ERR_SEND_RESP, self.stack_id, str(exc), self.response_url, resp) 
Example 5
Project: botbuilder-python   Author: microsoft   File: teams_file_bot.py    License: MIT License 6 votes vote down vote up
def on_teams_file_consent_accept(
            self,
            turn_context: TurnContext,
            file_consent_card_response: FileConsentCardResponse
    ):
        """
        The user accepted the file upload request.  Do the actual upload now.
        """

        file_path = "files/" + file_consent_card_response.context["filename"]
        file_size = os.path.getsize(file_path)

        headers = {
            "Content-Length": f"\"{file_size}\"",
            "Content-Range": f"bytes 0-{file_size-1}/{file_size}"
        }
        response = requests.put(
            file_consent_card_response.upload_info.upload_url, open(file_path, "rb"), headers=headers
        )

        if response.status_code != 200:
            await self._file_upload_failed(turn_context, "Unable to upload file.")
        else:
            await self._file_upload_complete(turn_context, file_consent_card_response) 
Example 6
Project: hsds   Author: HDFGroup   File: attr_test.py    License: Apache License 2.0 6 votes vote down vote up
def testPutInvalid(self):
        print("testPutInvalid", self.base_domain)
        headers = helper.getRequestHeaders(domain=self.base_domain)
        req = self.endpoint + '/'

        rsp = requests.get(req, headers=headers)
        self.assertEqual(rsp.status_code, 200)
        rspJson = json.loads(rsp.text)
        root_id = rspJson["root"]

        # try creating an attribute with an invalid type
        attr_name = "attr1"
        attr_payload = {'type': 'H5T_FOOBAR', 'value': 42}
        req = self.endpoint + "/groups/" + root_id + "/attributes/" + attr_name
        rsp = requests.put(req, data=json.dumps(attr_payload), headers=headers)
        self.assertEqual(rsp.status_code, 400)  # invalid request 
Example 7
Project: hsds   Author: HDFGroup   File: helper.py    License: Apache License 2.0 6 votes vote down vote up
def setupDomain(domain):
    endpoint = config.get("hsds_endpoint")
    print("setupdomain: ", domain)
    headers = getRequestHeaders(domain=domain)
    req = endpoint + "/"
    rsp = requests.get(req, headers=headers)
    if rsp.status_code == 200:
        return  # already have domain
    if rsp.status_code != 404:
        # something other than "not found"
        raise ValueError("Unexpected get domain error: {}".format(rsp.status_code))

    parent_domain = getParentDomain(domain)
    if parent_domain is None:
        raise ValueError("Invalid parent domain: {}".format(domain))
    # create parent domain if needed
    setupDomain(parent_domain)  
     
    headers = getRequestHeaders(domain=domain)
    rsp = requests.put(req, headers=headers)
    if rsp.status_code != 201:
        raise ValueError("Unexpected put domain error: {}".format(rsp.status_code)) 
Example 8
Project: evohome-client   Author: watchforstock   File: controlsystem.py    License: Apache License 2.0 6 votes vote down vote up
def _set_status(self, mode, until=None):
        # pylint: disable=protected-access
        headers = dict(self.client._headers())
        headers["Content-Type"] = "application/json"

        if until is None:
            data = {"SystemMode": mode, "TimeUntil": None, "Permanent": True}
        else:
            data = {
                "SystemMode": mode,
                "TimeUntil": until.strftime("%Y-%m-%dT%H:%M:%SZ"),
                "Permanent": False,
            }

        response = requests.put(
            "https://tccna.honeywell.com/WebAPI/emea/api/v1"
            "/temperatureControlSystem/%s/mode" % self.systemId,
            data=json.dumps(data),
            headers=headers,
        )
        response.raise_for_status() 
Example 9
Project: evohome-client   Author: watchforstock   File: zone.py    License: Apache License 2.0 6 votes vote down vote up
def set_schedule(self, zone_info):
        """Set the schedule for this zone."""
        # must only POST json, otherwise server API handler raises exceptions
        # pylint: disable=protected-access
        try:
            json.loads(zone_info)

        except ValueError as error:
            raise ValueError("zone_info must be valid JSON: ", error)

        headers = dict(self.client._headers())
        headers["Content-Type"] = "application/json"

        response = requests.put(
            "https://tccna.honeywell.com/WebAPI/emea/api/v1/%s/%s/schedule"
            % (self.zone_type, self.zoneId),
            data=zone_info,
            headers=headers,
        )
        response.raise_for_status()

        return response.json() 
Example 10
Project: evohome-client   Author: watchforstock   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def _set_heat_setpoint(self, zone, data):
        self._populate_full_data()

        device_id = self._get_device_id(zone)

        url = (
            self.hostname
            + "/WebAPI/api/devices/%s/thermostat/changeableValues/heatSetpoint"
            % device_id
        )

        response = self._do_request("put", url, json.dumps(data))

        task_id = self._get_task_id(response)

        while self._get_task_status(task_id) != "Succeeded":
            time.sleep(1) 
Example 11
Project: pyspider   Author: binux   File: test_run.py    License: Apache License 2.0 6 votes vote down vote up
def test_50_docker_rabbitmq(self):
        try:
            os.environ['RABBITMQ_NAME'] = 'rabbitmq'
            os.environ['RABBITMQ_PORT_5672_TCP_ADDR'] = 'localhost'
            os.environ['RABBITMQ_PORT_5672_TCP_PORT'] = '5672'
            ctx = run.cli.make_context('test', [], None,
                                       obj=dict(testing_mode=True))
            ctx = run.cli.invoke(ctx)
            queue = ctx.obj.newtask_queue
            queue.put('abc')
            queue.delete()
        except Exception as e:
            self.assertIsNone(e)
        finally:
            del os.environ['RABBITMQ_NAME']
            del os.environ['RABBITMQ_PORT_5672_TCP_ADDR']
            del os.environ['RABBITMQ_PORT_5672_TCP_PORT'] 
Example 12
Project: happn   Author: rickhousley   File: happn.py    License: MIT License 6 votes vote down vote up
def set_settings(self, settings):
        h=headers
        h.update({
          'Authorization'   : 'OAuth="'+ self.oauth + '"',
          'Content-Length'  :  '1089', #@TODO figure out length calculation
          'Content-Type'    : 'application/json'})

        # Happn preferences
        url = 'https://api.happn.fr/api/users/' + self.id
        try:
            r = requests.put(url, headers=h, data = json.dumps(settings))
        except Exception as e:
            raise HTTP_MethodError('Error Setting Settings: {}'.format(e))

        if r.status_code == 200: #200 = 'OK'
            logging.debug('Updated Settings')
        else:
            # Unable to fetch distance
            raise HTTP_MethodError(httpErrors[r.status_code]) 
Example 13
Project: happn   Author: rickhousley   File: happn.py    License: MIT License 6 votes vote down vote up
def update_activity(self):
        """ Updates User activity """

        # Create and send HTTP PUT to Happn server
        h = headers
        h.update({
            'Authorization' : 'OAuth="'+ self.oauth + '"',
            'Content-Type'  : 'application/x-www-form-urlencoded; charset=UTF-8',
            'Content-Length': '20'
        })
        payload = {
            'update_activity' :  'true'
        }
        url = 'https://api.happn.fr/api/users/'+self.id
        try:
            r = requests.put(url, headers=h, data = payload)
        except Exception as e:
            raise HTTP_MethodError('Error Connecting to Happn Server: {}'.format(e))

        if r.status_code == 200: #200 = 'OK'
            logging.debug('Updated User activity')
        else:
            # Unable to fetch distance
            raise HTTP_MethodError(httpErrors[r.status_code]) 
Example 14
Project: jumpserver-python-sdk   Author: jumpserver   File: request.py    License: GNU General Public License v2.0 5 votes vote down vote up
def put(self, *args, **kwargs):
        kwargs['method'] = 'put'
        return self.do(*args, **kwargs) 
Example 15
Project: CyberTK-Self   Author: CyberTKR   File: channel.py    License: GNU General Public License v2.0 5 votes vote down vote up
def changeAlbumName(self,gid,name,albumId):
        header = {
            "Content-Type" : "application/json",
            "X-Line-Mid" : self.mid,
            "x-lct": self.channel_access_token,

        }
        payload = {
            "title": name
        }
        r = requests.put(
            "http://" + self.host + "/mh/album/v3/album/" + albumId + "?homeId=" + gid,
            headers = header,
            data = json.dumps(payload),
        )
        return r.json() 
Example 16
Project: python-rest-api   Author: messagebird   File: http_client.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def request(self, path, method='GET', params=None, format=ResponseFormat.text):
        """Builds a request and gets a response."""
        if params is None:
            params = {}
        url = urljoin(self.endpoint, path)
        headers = {
            'Accept': 'application/json',
            'Authorization': 'AccessKey ' + self.access_key,
            'User-Agent': self.user_agent,
            'Content-Type': 'application/json'
        }

        method_switcher = {
            'DELETE': lambda: requests.delete(url, verify=True, headers=headers, data=json_serialize(params)),
            'GET': lambda: requests.get(url, verify=True, headers=headers, params=params),
            'PATCH': lambda: requests.patch(url, verify=True, headers=headers, data=json_serialize(params)),
            'POST': lambda: requests.post(url, verify=True, headers=headers, data=json_serialize(params)),
            'PUT': lambda: requests.put(url, verify=True, headers=headers, data=json_serialize(params))
        }
        if method not in method_switcher:
            raise ValueError(str(method) + ' is not a supported HTTP method')

        response = method_switcher[method]()

        if response.status_code not in self.__supported_status_codes:
            response.raise_for_status()

        response_switcher = {
            ResponseFormat.text: response.text,
            ResponseFormat.binary: response.content
        }
        return response_switcher.get(format) 
Example 17
Project: aws-waf-security-automations   Author: awslabs   File: helper.py    License: Apache License 2.0 5 votes vote down vote up
def send_response(event, context, responseStatus, responseData, resourceId, reason=None):
    logging.getLogger().debug("[send_response] Start")

    responseUrl = event['ResponseURL']
    cw_logs_url = "https://console.aws.amazon.com/cloudwatch/home?region=%s#logEventViewer:group=%s;stream=%s"%(context.invoked_function_arn.split(':')[3], context.log_group_name, context.log_stream_name)

    logging.getLogger().info(responseUrl)
    responseBody = {}
    responseBody['Status'] = responseStatus
    responseBody['Reason'] = reason or ('See the details in CloudWatch Logs: ' +  cw_logs_url)
    responseBody['PhysicalResourceId'] = resourceId
    responseBody['StackId'] = event['StackId']
    responseBody['RequestId'] = event['RequestId']
    responseBody['LogicalResourceId'] = event['LogicalResourceId']
    responseBody['NoEcho'] = False
    responseBody['Data'] = responseData

    json_responseBody = json.dumps(responseBody)
    logging.getLogger().debug("Response body:\n" + json_responseBody)

    headers = {
        'content-type' : '',
        'content-length' : str(len(json_responseBody))
    }

    try:
        response = requests.put(responseUrl,
                                data=json_responseBody,
                                headers=headers)
        logging.getLogger().debug("Status code: " + response.reason)

    except Exception as error:
        logging.getLogger().error("[send_response] Failed executing requests.put(..)")
        logging.getLogger().error(str(error))

    logging.getLogger().debug("[send_response] End")

#======================================================================================================================
# Lambda Entry Point
#====================================================================================================================== 
Example 18
Project: aws-waf-security-automations   Author: awslabs   File: custom-resource.py    License: Apache License 2.0 5 votes vote down vote up
def send_response(event, context, responseStatus, responseData, resourceId, reason=None):
    logging.getLogger().debug("[send_response] Start")

    responseUrl = event['ResponseURL']
    cw_logs_url = "https://console.aws.amazon.com/cloudwatch/home?region=%s#logEventViewer:group=%s;stream=%s"%(context.invoked_function_arn.split(':')[3], context.log_group_name, context.log_stream_name)

    logging.getLogger().info(responseUrl)
    responseBody = {}
    responseBody['Status'] = responseStatus
    responseBody['Reason'] = reason or ('See the details in CloudWatch Logs: ' +  cw_logs_url)
    responseBody['PhysicalResourceId'] = resourceId
    responseBody['StackId'] = event['StackId']
    responseBody['RequestId'] = event['RequestId']
    responseBody['LogicalResourceId'] = event['LogicalResourceId']
    responseBody['NoEcho'] = False
    responseBody['Data'] = responseData

    json_responseBody = json.dumps(responseBody)
    logging.getLogger().debug("Response body:\n" + json_responseBody)

    headers = {
        'content-type' : '',
        'content-length' : str(len(json_responseBody))
    }

    try:
        response = requests.put(responseUrl,
                                data=json_responseBody,
                                headers=headers)
        logging.getLogger().debug("Status code: " + response.reason)

    except Exception as error:
        logging.getLogger().error("[send_response] Failed executing requests.put(..)")
        logging.getLogger().error(str(error))

    logging.getLogger().debug("[send_response] End") 
Example 19
Project: pyfirebase   Author: afropolymath   File: firebase.py    License: MIT License 5 votes vote down vote up
def set(self, payload):
        return requests.put(self.current_url, json=payload) 
Example 20
Project: bit9platform   Author: carbonblack   File: bit9api.py    License: MIT License 5 votes vote down vote up
def update(self, api_obj, data, obj_id=0, url_params=''):
        if not data:
            raise TypeError("Missing object data.")
        if url_params:
            url_params = '?' + url_params.lstrip("?")
        if not obj_id:
            obj_id = data['id']
        url = self.server + '/' + api_obj + '/' + str(obj_id) + url_params
        r = requests.put(url, data=json.dumps(data), headers=self.tokenHeaderJson, verify=self.sslVerify)
        return self.__check_result(r)


    # Delete object using HTTP DELETE request. 
Example 21
Project: bitbucket-python   Author: GearPlug   File: client.py    License: MIT License 5 votes vote down vote up
def _put(self, endpoint, params=None, data=None):
        response = requests.put(self.BASE_URL + endpoint, params=params, json=data, auth=(self.user, self.password))
        return self._parse(response) 
Example 22
Project: Vxscan   Author: al0ne   File: http_put.py    License: Apache License 2.0 5 votes vote down vote up
def put(url):
    url = url.strip('/')
    text = random.randint(100000000, 200000000)
    payload = '/{}.txt'.format(text)
    url = url + payload
    data = {'{}'.format(text): '{}'.format(text)}
    r = requests.put(url, data=data, allow_redirects=False, verify=False, headers=get_ua())
    if r.status_code == 201:
        return 'HTTP METHOD PUT url: {}'.format(url) 
Example 23
Project: Vxscan   Author: al0ne   File: http_put.py    License: Apache License 2.0 5 votes vote down vote up
def check(url, ip, ports, apps):
    result = ''
    try:
        probe = get_list(ip, ports)
        for url in probe:
            result = put(url)
    except Exception as e:
        pass
    if result:
        return result 
Example 24
Project: python-consul2   Author: poppyred   File: conftest.py    License: MIT License 5 votes vote down vote up
def clean_consul(port, token=''):
    # remove all data from the instance, to have a clean start
    base_uri = 'http://127.0.0.1:%s/v1/' % port
    params = {'recurse': 1}
    if token:
        params['token'] = token
    requests.delete(base_uri + 'kv/', params=params)
    services = requests.get(base_uri + 'agent/services',
                            params=params).json().keys()
    for s in services:
        requests.put(base_uri + 'agent/service/deregister/%s' % s)

    if token:
        acl_tokens = requests.get(base_uri + 'acl/list', params=params).json()
        for t in acl_tokens:
            if t['ID'] != token:
                requests.put(base_uri + 'acl/destroy/%s' % t['ID'],
                             params=params)

        acl_policys = requests.get(base_uri + 'acl/policies',
                                   params=params).json()
        for pls in acl_policys:
            if pls['ID'] != token:
                requests.delete(base_uri + 'acl/policy/%s' % pls['ID'],
                                params=params)

        acl_roles = requests.get(base_uri + 'acl/roles',
                                 params=params).json()
        for role in acl_roles:
            if role['ID'] != token:
                requests.delete(base_uri + 'acl/role/%s' % role['ID'],
                                params=params) 
Example 25
Project: apsconnect-cli   Author: cloudblue   File: hub.py    License: Apache License 2.0 5 votes vote down vote up
def put(self, uri, json=None):
        return requests.put('{}/{}'.format(self.url, uri), headers=self.token, json=json,
                            verify=False) 
Example 26
Project: ZhihuVAPI   Author: cheezone   File: zhihu.py    License: MIT License 5 votes vote down vote up
def jsonput(url, data={}, *arg):
    """
    自动将 PUT 请求转换为 JSON
    """
    if url.__class__.__name__ == 'function':
        url = url()
    try:
        return json_moudle.loads(requests.put(url, *arg, data=data, headers=Session.headers,
                                              verify=verify, timeout=3).text)
    except json_moudle.decoder.JSONDecodeError as e:
        log(f'JSON 解析错误,请检查知乎 API 的 URL 是否变化,当前 URL 为:{url}') 
Example 27
Project: hsds   Author: HDFGroup   File: dataset_test.py    License: Apache License 2.0 5 votes vote down vote up
def testCompound(self):
        # test Dataset with compound type
        domain = self.base_domain + "/testCompound.h5"
        helper.setupDomain(domain)
        print("testCompound", domain)
        headers = helper.getRequestHeaders(domain=domain)

        # get domain
        req = helper.getEndpoint() + '/'
        rsp = requests.get(req, headers=headers)
        rspJson = json.loads(rsp.text)
        self.assertTrue("root" in rspJson)
        root_uuid = rspJson["root"]

        fields = ({'name': 'temp', 'type': 'H5T_STD_I32LE'},
                    {'name': 'pressure', 'type': 'H5T_IEEE_F32LE'})
        datatype = {'class': 'H5T_COMPOUND', 'fields': fields }
        payload = {'type': datatype, 'shape': 10}
        req = self.endpoint + "/datasets"
        rsp = requests.post(req, data=json.dumps(payload), headers=headers)
        self.assertEqual(rsp.status_code, 201)  # create dataset
        rspJson = json.loads(rsp.text)
        dset_uuid = rspJson['id']
        self.assertTrue(helper.validateId(dset_uuid))

        # link the new dataset
        name = "dset"
        req = self.endpoint + "/groups/" + root_uuid + "/links/" + name
        payload = {"id": dset_uuid}
        rsp = requests.put(req, data=json.dumps(payload), headers=headers)
        self.assertEqual(rsp.status_code, 201) 
Example 28
Project: hsds   Author: HDFGroup   File: attr_test.py    License: Apache License 2.0 5 votes vote down vote up
def testEmptyShapeAttr(self):
        print("testEmptyShapeAttr", self.base_domain)
        headers = helper.getRequestHeaders(domain=self.base_domain)
        req = helper.getEndpoint() + '/'

        rsp = requests.get(req, headers=headers)
        self.assertEqual(rsp.status_code, 200)
        rspJson = json.loads(rsp.text)
        root_uuid = rspJson["root"]
        helper.validateId(root_uuid)

        attr_name = "attr_empty_shape"
        attr_payload = {'type': 'H5T_STD_I32LE', 'shape': [], 'value': 42}
        req = self.endpoint + "/groups/" + root_uuid + "/attributes/" + attr_name
        rsp = requests.put(req, headers=headers, data=json.dumps(attr_payload))
        self.assertEqual(rsp.status_code, 201)  # created

        # read back the attribute
        rsp = requests.get(req, headers=headers)
        self.assertEqual(rsp.status_code, 200)  # OK
        rspJson = json.loads(rsp.text)
        self.assertTrue("name" in rspJson)
        self.assertEqual(rspJson["name"], "attr_empty_shape")
        self.assertTrue("type" in rspJson)
        attr_type = rspJson["type"]
        self.assertEqual(attr_type["base"], "H5T_STD_I32LE")
        self.assertTrue("hrefs" in rspJson)
        self.assertEqual(len(rspJson["hrefs"]), 3)
        self.assertTrue("value" in rspJson)
        self.assertEqual(rspJson["value"], 42)
        self.assertTrue("shape" in rspJson)
        attr_shape = rspJson["shape"]
        self.assertTrue("class" in attr_shape)
        self.assertEqual(attr_shape["class"], "H5S_SCALAR") 
Example 29
Project: hsds   Author: HDFGroup   File: attr_test.py    License: Apache License 2.0 5 votes vote down vote up
def testPutVLenString(self):
        # Test PUT value for 1d attribute with variable length string types
        print("testPutVLenString", self.base_domain)

        headers = helper.getRequestHeaders(domain=self.base_domain)
        req = self.endpoint + '/'

        # Get root uuid
        rsp = requests.get(req, headers=headers)
        self.assertEqual(rsp.status_code, 200)
        rspJson = json.loads(rsp.text)
        root_uuid = rspJson["root"]
        helper.validateId(root_uuid)

        # create attr
        words = ["Parting", "is such", "sweet", "sorrow."]
        fixed_str_type = {"charSet": "H5T_CSET_ASCII",
                "class": "H5T_STRING",
                "length": "H5T_VARIABLE",
                "strPad": "H5T_STR_NULLTERM" }
        data = { "type": fixed_str_type, "shape": 4,
            "value": words}
        attr_name = "str_attr"
        req = self.endpoint + "/groups/" + root_uuid + "/attributes/" + attr_name
        rsp = requests.put(req, data=json.dumps(data), headers=headers)
        self.assertEqual(rsp.status_code, 201)

        # read attr
        rsp = requests.get(req, headers=headers)
        self.assertEqual(rsp.status_code, 200)
        rspJson = json.loads(rsp.text)
        self.assertTrue("hrefs" in rspJson)
        self.assertTrue("value" in rspJson)
        self.assertEqual(rspJson["value"], words)
        self.assertTrue("type" in rspJson)
        type_json = rspJson["type"]
        self.assertTrue("class" in type_json)
        self.assertEqual(type_json["class"], "H5T_STRING")
        self.assertTrue("length" in type_json)
        self.assertEqual(type_json["length"], "H5T_VARIABLE") 
Example 30
Project: hsds   Author: HDFGroup   File: attr_test.py    License: Apache License 2.0 5 votes vote down vote up
def testGetAttributeJsonValue(self):
        # Test GET Attribute value with JSON response
        print("testGetAttributeJsonValue", self.base_domain)

        headers = helper.getRequestHeaders(domain=self.base_domain)
        req = self.endpoint + '/'

        # Get root uuid
        rsp = requests.get(req, headers=headers)
        self.assertEqual(rsp.status_code, 200)
        rspJson = json.loads(rsp.text)
        root_uuid = rspJson["root"]
        helper.validateId(root_uuid)

        # create attr
        value = [2,3,5,7,11,13]
        data = { "type": 'H5T_STD_I32LE', "shape": 6, "value": value}
        attr_name = "int_arr_attr"
        req = self.endpoint + "/groups/" + root_uuid + "/attributes/" + attr_name
        rsp = requests.put(req, data=json.dumps(data), headers=headers)
        self.assertEqual(rsp.status_code, 201)

        # read attr
        req = self.endpoint + "/groups/" + root_uuid + "/attributes/" + attr_name + "/value"
        rsp = requests.get(req, headers=headers)
        self.assertEqual(rsp.status_code, 200)
        rspJson = json.loads(rsp.text)
        self.assertTrue("hrefs" in rspJson)
        self.assertTrue("value" in rspJson)
        self.assertFalse("type" in rspJson)
        self.assertFalse("shape" in rspJson)
        self.assertEqual(rspJson["value"], value)