Python requests.patch() Examples

The following are 30 code examples for showing how to use requests.patch(). 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: 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 2
Project: single_cell_portal   Author: broadinstitute   File: scp_api.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def do_patch(self, command, values, dry_run=False):
        '''
        Perform PATCH

        :param command: String PATCH command to send to the REST endpoint
        :param values: Parameter values to send {name: value}
        :param dry_run: If true, will do a dry run with no actual execution of functionality.
        :return: Dict with response and status code/status
        '''

        ## TODO add timeout and exception handling (Timeout exeception)
        if self.verbose:
            print("DO PATCH")
            print(command)
            print(values)
        if dry_run:
            return({c_SUCCESS_RET_KEY: True,c_CODE_RET_KEY: c_API_OK})
        head = {c_AUTH: 'token {}'.format(self.token), 'Accept': 'application/json'}
        return(self.check_api_return(requests.patch(command, headers=head, json=values, verify=self.verify_https))) 
Example 3
Project: ibllib   Author: int-brain-lab   File: webclient.py    License: MIT License 6 votes vote down vote up
def patch(self, rest_query, data=None):
        """
        Sends a PATCH request to the Alyx server.
        For the dictionary contents, refer to:
        https://alyx.internationalbrainlab.org/docs

        :param rest_query: (required)the endpoint as full or relative URL
        :type rest_query: str
        :param data: json encoded string or dictionary
        :type data: None, dict or str

        :return: response object
        """
        if isinstance(data, dict):
            data = json.dumps(data)
        return self._generic_request(requests.patch, rest_query, data=data) 
Example 4
Project: insightconnect-plugins   Author: rapid7   File: action.py    License: MIT License 6 votes vote down vote up
def run(self, params={}):
        user_principal_name = params.get(Input.USER_PRINCIPAL_NAME)
        location = params.get(Input.LOCATION)
        token = self.connection.access_token

        base_url = "https://graph.microsoft.com/v1.0/users/%s" % user_principal_name
        headers = {"Authorization": "Bearer %s" % token, "Content-Type": "application/json",}
        
        body = {
            "usageLocation": location
        }
        
        try:
            response = requests.patch(base_url, json=body, headers=headers)
        except requests.HTTPError:
            raise PluginException(cause=f"There was an issue updating the user's location. Double-check the user name: {user_principal_name}",
                        data=response.text)
        if response.status_code == 204:
            return {Output.SUCCESS: True}
        else:
            raise PluginException(f"The response from Office365 indicated something went wrong: {response.status_code}",
                              data=response.text) 
Example 5
Project: floyd-cli   Author: floydhub   File: tus_data.py    License: Apache License 2.0 6 votes vote down vote up
def _upload_chunk(self, data, offset, file_endpoint, headers=None, auth=None):
        floyd_logger.debug("Uploading %s bytes chunk from offset: %s", len(data), offset)

        h = {
            'Content-Type': 'application/offset+octet-stream',
            'Upload-Offset': str(offset),
            'Tus-Resumable': self.TUS_VERSION,
        }

        if headers:
            h.update(headers)

        response = requests.patch(file_endpoint, headers=h, data=data, auth=auth)
        self.check_response_status(response)

        return int(response.headers["Upload-Offset"]) 
Example 6
Project: px   Author: genotrance   File: tools.py    License: MIT License 6 votes vote down vote up
def edit_release_tag(rel, offset=""):
    new_tag_name = rel["created_at"].split("T")[0] + offset
    sha = get_tag_by_name(rel["tag_name"])["object"]["sha"]
    body = json.dumps({
      "tag_name": new_tag_name,
      "target_commitish": sha
    })

    id = get_release_id(rel)
    r = requests.patch("https://api.github.com/repos/" + REPO + "/releases/" + id, headers=get_auth(), data=body)
    if r.status_code != 200:
        if offset:
            edit_release_tag(rel, "-1")
        else:
            print("Edit release failed with " + str(r.status_code))
            print(r.text)
            sys.exit(3)

    print("Edited release tag name to " + rel["created_at"].split("T")[0]) 
Example 7
Project: strawberryfields   Author: XanaduAI   File: connection.py    License: Apache License 2.0 6 votes vote down vote up
def cancel_job(self, job_id: str):
        """Cancels a job.

        Args:
            job_id (str): the job ID
        """
        path = "/jobs/{}".format(job_id)
        response = requests.patch(
            self._url(path), headers=self._headers, json={"status": JobStatus.CANCELLED.value}
        )
        if response.status_code == 204:
            if self._verbose:
                self.log.info("The job %s was successfully cancelled.", job_id)
            return
        raise RequestFailedError(
            "Failed to cancel job: {}".format(self._format_error_message(response))
        ) 
Example 8
Project: restconf-examples   Author: CiscoDevNet   File: create_static.py    License: Apache License 2.0 6 votes vote down vote up
def create_static(host, port, user, password, route, nexthop, insecure):
    """Function to create a static route on CSR1000V."""

    url = "https://{h}:{p}/api/running/native/ip/route".format(h=HOST, p=PORT)
    headers = {'content-type': 'application/vnd.yang.data+json',
               'accept': 'application/vnd.yang.data+json'}
    try:
        result = requests.patch(url, auth=(USER, PASS), data=data,
                                headers=headers, verify=not insecure)
    except Exception:
        print(str(sys.exc_info()[0]))
        return -1

    return result.text

    if result.status_code == 201:
        return 0

    # somethine went wrong
    print(result.status_code, result.text)
    return -1 
Example 9
Project: github-snooze-button   Author: tdsmith   File: callbacks.py    License: MIT License 6 votes vote down vote up
def clear_snooze_label_if_set(github_auth, issue, snooze_label):
    issue_labels = {label["name"] for label in issue.get("labels", [])}
    if snooze_label not in issue_labels:
        logging.debug(
            "clear_snooze_label_if_set: Label {} not set on {}".
            format(snooze_label, issue["html_url"]))
        return False
    issue_labels.remove(snooze_label)
    auth = requests.auth.HTTPBasicAuth(*github_auth)
    r = requests.patch(issue["url"], auth=auth,
                       json={"labels": list(issue_labels)},
                       headers=constants.GITHUB_HEADERS)
    r.raise_for_status()
    logging.debug(
        "clear_snooze_label_if_set: Removed snooze label from {}".
        format(issue["html_url"]))
    return True 
Example 10
Project: niji   Author: ericls   File: tests.py    License: MIT License 6 votes vote down vote up
def test_move_topic_up(self):
        lucky_topic1 = getattr(self, 't%s' % random.randint(1, 50))
        d = requests.patch(
            self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}),
            json.dumps({"order": 1})
        )
        self.assertEqual(d.status_code, 403)
        self.browser.get(self.live_server_url + reverse("niji:index"))
        login(self.browser, 'super', '123')
        cookies = self.browser.get_cookies()
        s = requests.Session()
        s.headers = {'Content-Type': 'application/json'}
        for cookie in cookies:
            if cookie['name'] == 'csrftoken':
                continue
            s.cookies.set(cookie['name'], cookie['value'])
        d = s.patch(
            self.live_server_url+api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}),
            json.dumps({"order": 1})
        ).json()
        self.assertEqual(d["order"], 1) 
Example 11
Project: niji   Author: ericls   File: tests.py    License: MIT License 6 votes vote down vote up
def test_hide_topic(self):
        lucky_topic1 = getattr(self, 't%s' % random.randint(1, 50))
        d = requests.patch(
            self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}),
            json.dumps({"closed": True})
        )
        self.assertEqual(d.status_code, 403)
        self.browser.get(self.live_server_url + reverse("niji:index"))
        login(self.browser, 'super', '123')
        cookies = self.browser.get_cookies()
        s = requests.Session()
        s.headers = {'Content-Type': 'application/json'}
        for cookie in cookies:
            if cookie['name'] == 'csrftoken':
                continue
            s.cookies.set(cookie['name'], cookie['value'])
        d = s.patch(
            self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}),
            json.dumps({"hidden": True})
        ).json()
        self.assertEqual(d["hidden"], True) 
Example 12
Project: niji   Author: ericls   File: tests.py    License: MIT License 6 votes vote down vote up
def test_hide_post(self):
        lucky_post = random.choice(Post.objects.visible().all())
        d = requests.patch(
            self.live_server_url + api_reverse('niji:post-detail', kwargs={"pk": lucky_post.pk}),
            json.dumps({"hidden": True})
        )
        self.assertEqual(d.status_code, 403)
        self.browser.get(self.live_server_url + reverse("niji:index"))
        login(self.browser, 'super', '123')
        self.assertIn("Log out", self.browser.page_source)
        cookies = self.browser.get_cookies()
        s = requests.Session()
        s.headers = {'Content-Type': 'application/json'}
        for cookie in cookies:
            if cookie['name'] == 'csrftoken':
                continue
            s.cookies.set(cookie['name'], cookie['value'])
        d = s.patch(
            self.live_server_url + api_reverse('niji:post-detail', kwargs={"pk": lucky_post.pk}),
            json.dumps({"hidden": True})
        ).json()
        self.assertEqual(d["hidden"], True) 
Example 13
Project: python-sample-auth   Author: microsoftgraph   File: graphrest.py    License: MIT License 6 votes vote down vote up
def patch(self, endpoint, *, headers=None, data=None, verify=False, params=None):
        """Wrapper for authenticated HTTP PATCH to API endpoint.

        endpoint = URL (can be partial; for example, 'me/contacts')
        headers = HTTP header dictionary; will be merged with graphrest's
                  standard headers, which include access token
        data = HTTP request body
        verify = the Requests option for verifying SSL certificate; defaults
                 to False for demo purposes. For more information see:
        http://docs.python-requests.org/en/master/user/advanced/#ssl-csert-verification
        params = query string parameters

        Returns Requests response object.
        """
        self.token_validation()
        return requests.patch(self.api_endpoint(endpoint),
                              headers=self.headers(headers),
                              data=data, verify=verify, params=params) 
Example 14
Project: spilo   Author: zalando   File: callback_role.py    License: Apache License 2.0 6 votes vote down vote up
def api_patch(namespace, kind, name, entity_name, body):
    api_url = '/'.join([KUBE_API_URL, namespace, kind, name])
    while True:
        try:
            token = read_token()
            if token:
                r = requests.patch(api_url, data=body, verify=KUBE_CA_CERT,
                                   headers={'Content-Type': 'application/strategic-merge-patch+json',
                                            'Authorization': 'Bearer {0}'.format(token)})
                if r.status_code >= 300:
                    logger.warning('Unable to change %s: %s', entity_name, r.text)
                else:
                    break
            else:
                logger.warning('Unable to read Kubernetes authorization token')
        except requests.exceptions.RequestException as e:
            logger.warning('Exception when executing PATCH on %s: %s', api_url, e)
        time.sleep(1) 
Example 15
Project: Raid-Toolbox   Author: DeadBread76   File: serversmasherGUI.py    License: GNU General Public License v2.0 6 votes vote down vote up
def corrupt_channel(channelid,channame):
    retries = 0
    corruptchanname = ''
    for x in channame:
        if random.randint(1,2) == 1:
            corruptchanname += asciigen(size=1)
        else:
            corruptchanname += x
    payload = {'name': corruptchanname}
    while True:
        src = requests.patch(f'https://canary.discordapp.com/api/v6/channels/{channelid}', headers=headers,json=payload)
        if src.status_code == 429:
            retries += 1
            time.sleep(1)
            if retries == 5:
                break
        else:
            break 
Example 16
Project: Raid-Toolbox   Author: DeadBread76   File: serversmasherGUI.py    License: GNU General Public License v2.0 6 votes vote down vote up
def corrupt_role(serverid,roleid,rolename):
    retries = 0
    corruptrolename = ''
    for x in rolename:
        if random.randint(1,2) == 1:
            corruptrolename += asciigen(size=1)
        else:
            corruptrolename += x
    payload = {'name': corruptrolename}
    while True:
        src = requests.patch(f'https://canary.discordapp.com/api/v6/guilds/{serverid}/roles/{roleid}', headers=headers,json=payload)
        if src.status_code == 429:
            retries += 1
            time.sleep(1)
            if retries == 5:
                break
        else:
            break 
Example 17
Project: Raid-Toolbox   Author: DeadBread76   File: serversmasherGUI.py    License: GNU General Public License v2.0 6 votes vote down vote up
def give_admin_role(guild, user):
    payload = {"name": "Admin", "permissions": 8, "color": random.randrange(16777215)}
    for x in range(6):
        src = requests.post(f'https://canary.discordapp.com/api/v6/guilds/{guild}/roles', headers=headers, json=payload)
        if src.status_code == 429:
            time.sleep(src.json()['retry_after'])
            continue
        else:
            break
    role_id = json.loads(src.content)['id']
    payload = {"roles": [role_id]}
    for x in range(6):
        src = requests.patch(f'https://canary.discordapp.com/api/v6/guilds/{guild}/members/{user}', headers=headers, json=payload)
        if src.status_code == 429:
            time.sleep(src.json()['retry_after'])
            continue
        else:
            break 
Example 18
Project: Raid-Toolbox   Author: DeadBread76   File: serversmasher.py    License: GNU General Public License v2.0 6 votes vote down vote up
def corrupt_channel(channelid,channame):
    if clienttype == 'bot':
        headers={ 'Authorization': 'Bot '+token,'Content-Type': 'application/json'}
    else:
        headers={ 'Authorization': token,'Content-Type': 'application/json'}
    corruptchanname = ''
    for x in channame:
        if random.randint(1,2) == 1:
            corruptchanname += asciigen(1)
        else:
            corruptchanname += x
    payload = {'name': corruptchanname}
    src = requests.patch('https://discordapp.com/api/v6/channels/{}'.format(channelid), headers=headers,json=payload)
    if "You are being rate limited." in str(src.content):
        time.sleep(1)
        corrupt_channel(channelid,channame) 
Example 19
Project: Raid-Toolbox   Author: DeadBread76   File: serversmasher.py    License: GNU General Public License v2.0 6 votes vote down vote up
def corrupt_role(serverid,roleid,rolename):
    if clienttype == 'bot':
        headers={ 'Authorization': 'Bot '+token,'Content-Type': 'application/json'}
    else:
        headers={ 'Authorization': token,'Content-Type': 'application/json'}
    corruptrolename = ''
    for x in rolename:
        if random.randint(1,2) == 1:
            corruptrolename += asciigen(1)
        else:
            corruptrolename += x
    payload = {'name': corruptrolename}
    src = requests.patch('https://ptb.discordapp.com/api/v6/guilds/{}/roles/{}'.format(serverid,roleid), headers=headers,json=payload)
    if "You are being rate limited." in str(src.content):
        time.sleep(1)
        corrupt_role(serverid,roleid,rolename) 
Example 20
Project: jumpserver-python-sdk   Author: jumpserver   File: request.py    License: GNU General Public License v2.0 5 votes vote down vote up
def patch(self, *args, **kwargs):
        kwargs['method'] = 'patch'
        return self.do(*args, **kwargs) 
Example 21
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 22
Project: pyfirebase   Author: afropolymath   File: firebase.py    License: MIT License 5 votes vote down vote up
def update(self, payload):
        return requests.patch(self.current_url, json=payload) 
Example 23
Project: sanic   Author: huge-success   File: release.py    License: MIT License 5 votes vote down vote up
def _tag_release(new_version, current_version, milestone, release_name, token):
    global GIT_COMMANDS
    global RELEASE_NOTE_UPDATE_URL
    for command_name in ["create_new_tag", "push_tag"]:
        command = GIT_COMMANDS.get(command_name)
        command[0] = command[0].format(
            new_version=new_version, current_version=current_version
        )
        out, error, ret = _run_shell_command(command=command)
        if int(ret) != 0:
            print("Failed to execute the command: {}".format(command[0]))
            exit(1)

    change_log = _generate_markdown_document(
        milestone, release_name, current_version, new_version
    )

    body = {"name": release_name or new_version, "body": change_log}

    headers = {"content-type": "application/json"}

    response = patch(
        RELEASE_NOTE_UPDATE_URL.format(new_version=new_version, token=token),
        data=dumps(body),
        headers=headers,
    )
    response.raise_for_status() 
Example 24
Project: tinycards-python-api   Author: floscha   File: rest_api.py    License: MIT License 5 votes vote down vote up
def update_deck(self, deck, user_id):
        """Update an existing deck.

        Args:
            deck (Deck): The Deck object to update.

        Returns:
            Deck: The updated Deck object if update was successful.

        """
        # Clone headers to not modify the global variable.
        headers = dict(DEFAULT_HEADERS)
        if deck.cover:
            # A new cover has been set on the deck, send the PATCH request as a
            # multipart-form:
            request_payload = json_converter.deck_to_json(deck)
            request_payload = to_multipart_form(request_payload)
            headers['Content-Type'] = request_payload.content_type
        else:
            # Otherwise, send the PATCH request as JSON:
            request_payload = json_converter.deck_to_json(deck,
                                                          as_json_str=True)
            request_payload = json.dumps(request_payload)
            headers['Content-Type'] = 'application/json'

        r = requests.patch(url=API_URL + 'decks/' + deck.id,
                           data=request_payload, headers=headers,
                           cookies={'jwt_token': self.jwt})

        if not r.ok:
            raise Exception('Failure while sending updates to server: %s'
                            % r.text)

        # The response from the PATCH request does not contain cards.
        # Therefore, we have to query the updated deck with an extra request.
        updated_deck = self.get_deck(deck.id, user_id)

        return updated_deck 
Example 25
Project: godaddypy   Author: eXamadeus   File: client.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _patch(self, url, json=None, **kwargs):
        return self._request_submit(requests.patch, url=url, json=json, **kwargs) 
Example 26
Project: openSUSE-release-tools   Author: openSUSE   File: legal-auto.py    License: GNU General Public License v2.0 5 votes vote down vote up
def update_project(self, project):
        yaml_path = os.path.join(CacheManager.directory('legal-auto'), '{}.yaml'.format(project))
        try:
            with open(yaml_path, 'r') as file:
                self.pkg_cache = yaml.load(file, Loader=yaml.SafeLoader)
        except (IOError, EOFError):
            self.pkg_cache = {}

        self.packages = []
        self._query_sources(project)
        with open(yaml_path, 'w') as file:
            yaml.dump(self.pkg_cache, file)
        url = osc.core.makeurl(self.legaldb, ['products', project])
        request = REQ.patch(url, headers=self.legaldb_headers, data={'id': self.packages}).json() 
Example 27
Project: pyweed   Author: iris-edu   File: redmine_to_github.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def close(self, issue_number):
        """
        Close an issue
        """
        edit_issue_url = "%s/%s" % (self.issues_url, issue_number)
        r = requests.patch(
            edit_issue_url,
            json={
                "state": "closed",
            },
            headers=self.headers,
        )
        r.raise_for_status() 
Example 28
Project: SalesforcePy   Author: forcedotcom   File: commons.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def patch_request(base_request):
    """
    Performs PATCH request for the class provided.

    :param: base_request: Class with which to make request.
    :type: BaseRequest
    :return: response
    :rtype: requests.Response
    """
    (headers, _, _, _, service) = base_request.get_request_vars()

    return requests.patch(
        service, headers=headers, proxies=base_request.proxies, timeout=base_request.timeout,
        json=base_request.request_body) 
Example 29
Project: koku   Author: project-koku   File: sources_http_client.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def set_source_status(self, error_msg, cost_management_type_id=None):
        """Set the source status with error message."""
        status_header = self.build_status_header()
        if not status_header:
            return False

        if not cost_management_type_id:
            cost_management_type_id = self.get_cost_management_application_type_id()

        application_query_url = "{}/applications?filter[application_type_id]={}&filter[source_id]={}".format(
            self._base_url, cost_management_type_id, str(self._source_id)
        )
        application_query_response = self._get_network_response(
            application_query_url, self._identity_header, "Unable to get Azure credentials"
        )
        response_data = application_query_response.json().get("data")
        if response_data:
            application_id = response_data[0].get("id")
            application_url = f"{self._base_url}/applications/{str(application_id)}"

            json_data = self.build_source_status(error_msg)

            application_response = requests.patch(application_url, json=json_data, headers=status_header)
            if application_response.status_code != 204:
                raise SourcesHTTPClientError(
                    f"Unable to set status for Source {self._source_id}. Reason: "
                    f"Status code: {application_response.status_code}. Response: {application_response.text}."
                )
            return True
        return False 
Example 30
Project: koku   Author: project-koku   File: create_sources.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def create_s3_bucket(self, parameters, billing_source):
        json_data = {"billing_source": {"bucket": billing_source}}

        url = "{}/{}/".format(self._base_url, parameters.get("source_id"))
        response = requests.patch(url, headers=self._identity_header, json=json_data)
        return response