Python requests.put() Examples

The following are 30 code examples of requests.put(). 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 also want to check out all available functions/classes of the module requests , or try the search function .
Example #1
Source File: helper.py    From hsds with Apache License 2.0 9 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
Source File: attr_test.py    From hsds with Apache License 2.0 7 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 #3
Source File: firebase.py    From pyfirebase with 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 #4
Source File: unicorn_binance_websocket_api_restclient.py    From unicorn-binance-websocket-api with 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 #5
Source File: custom_resource.py    From aws-ops-automator with 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 #6
Source File: teams_file_bot.py    From botbuilder-python with 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 #7
Source File: helper.py    From hsds with 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
Source File: controlsystem.py    From evohome-client with 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
Source File: zone.py    From evohome-client with 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
Source File: __init__.py    From evohome-client with 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
Source File: test_run.py    From pyspider with 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
Source File: test_run.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def test_60a_docker_couchdb(self):
        try:
            # create a test admin user
            import requests
            requests.put('http://localhost:5984/_node/_local/_config/admins/test',
                         data='"password"')
            os.environ['COUCHDB_NAME'] = 'couchdb'
            os.environ['COUCHDB_PORT_5984_TCP_ADDR'] = 'localhost'
            os.environ['COUCHDB_PORT_5984_TCP_PORT'] = '5984'
            os.environ["COUCHDB_USER"] = "test"
            os.environ["COUCHDB_PASSWORD"] = "password"
            ctx = run.cli.make_context('test', [], None,
                                       obj=dict(testing_mode=True))
            ctx = run.cli.invoke(ctx)
            ctx.obj.resultdb
        except Exception as e:
            self.assertIsNone(e)
        finally:
            # remove the test admin user
            import requests
            from requests.auth import HTTPBasicAuth
            requests.delete('http://localhost:5984/_node/_local/_config/admins/test',
                            auth=HTTPBasicAuth('test', 'password'))
            del os.environ['COUCHDB_NAME']
            del os.environ['COUCHDB_PORT_5984_TCP_ADDR']
            del os.environ['COUCHDB_PORT_5984_TCP_PORT']
            del os.environ["COUCHDB_USER"]
            del os.environ["COUCHDB_PASSWORD"] 
Example #13
Source File: couchdbbase.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def insert_doc(self, db_name, doc_id, doc):
        url = self.base_url + db_name + "/" + doc_id
        return requests.put(url,
                            data=json.dumps(doc),
                            headers={"Content-Type": "application/json"},
                            auth=HTTPBasicAuth(self.username, self.password)).json() 
Example #14
Source File: couchdbbase.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def update_doc(self, db_name, doc_id, new_doc):
        doc = self.get_doc(db_name, doc_id)
        if doc is None:
            return self.insert_doc(db_name, doc_id, new_doc)
        for key in new_doc:
            doc[key] = new_doc[key]
        url = self.base_url + db_name + "/" + doc_id
        return requests.put(url,
                            data=json.dumps(doc),
                            headers={"Content-Type": "application/json"},
                            auth=HTTPBasicAuth(self.username, self.password)).json() 
Example #15
Source File: projectdb.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def __init__(self, url, database='projectdb', username='username', password='password'):
        self.username = username
        self.password = password
        self.url = url + self.__collection_name__ + "_" + database + "/"
        self.database = database
        self.insert('', {})

        # Create the db
        res = requests.put(self.url,
                           headers={"Content-Type": "application/json"},
                           auth=HTTPBasicAuth(self.username, self.password)).json()
        if 'error' in res and res['error'] == 'unauthorized':
            raise Exception(
                "Supplied credentials are incorrect. Reason: {} for User: {} Password: {}".format(res['reason'],
                                                                                                  self.username,
                                                                                                  self.password))
        # create index
        payload = {
            'index': {
                'fields': ['name']
            },
            'name': self.__collection_name__ + "_" + database
        }
        res = requests.post(self.url+"_index", data=json.dumps(payload),
                            headers={"Content-Type": "application/json"},
                            auth=HTTPBasicAuth(self.username, self.password)).json()
        self.index = res['id'] 
Example #16
Source File: projectdb.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def insert(self, name, obj={}):
        url = self.url + name
        obj = dict(obj)
        obj['name'] = name
        obj['updatetime'] = time.time()
        res = requests.put(url,
                           data = json.dumps(obj),
                           headers = {"Content-Type": "application/json"},
                           auth=HTTPBasicAuth(self.username, self.password)).json()
        return res 
Example #17
Source File: happn.py    From happn with 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 #18
Source File: happn.py    From happn with 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 #19
Source File: request.py    From jumpserver-python-sdk with 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 #20
Source File: channel.py    From CyberTK-Self with 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 #21
Source File: http_client.py    From python-rest-api with 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 #22
Source File: helper.py    From aws-waf-security-automations with 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 #23
Source File: custom-resource.py    From aws-waf-security-automations with 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 #24
Source File: firebase.py    From pyfirebase with MIT License 5 votes vote down vote up
def set(self, payload):
        return requests.put(self.current_url, json=payload) 
Example #25
Source File: bit9api.py    From bit9platform with 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 #26
Source File: client.py    From bitbucket-python with 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 #27
Source File: http_put.py    From Vxscan with 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 #28
Source File: http_put.py    From Vxscan with 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 #29
Source File: conftest.py    From python-consul2 with 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 #30
Source File: hub.py    From apsconnect-cli with 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)