requests.put

Here are the examples of the python api requests.put taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

186 Examples 7

Example 1

Project: commissaire-mvp Source File: cluster.py
Function: impl
@when('we initiate {async_operation} of cluster {cluster}')
def impl(context, async_operation, cluster):
    context.cluster = cluster
    if async_operation == 'an upgrade':
        context.request = requests.put(
            context.SERVER + '/api/v0/cluster/{0}/upgrade'.format(cluster),
            auth=context.auth)
    elif async_operation == 'a restart':
        context.request = requests.put(
            context.SERVER + '/api/v0/cluster/{0}/restart'.format(cluster),
            auth=context.auth)
    elif async_operation == 'a tree deployment':
        context.request = requests.put(
            context.SERVER + '/api/v0/cluster/{0}/deploy'.format(cluster),
            auth=context.auth,
            data=json.dumps({'version': '1.2.3'}))
    else:
        raise NotImplementedError

Example 2

Project: smart_open Source File: smart_open_lib.py
    def __init__(self, parsed_uri, min_part_size=WEBHDFS_MIN_PART_SIZE):
        if parsed_uri.scheme not in ("webhdfs"):
            raise TypeError("can only process WebHDFS files")
        self.parsed_uri = parsed_uri
        self.closed = False
        self.min_part_size = min_part_size
        # creating empty file first
        payload = {"op": "CREATE", "overwrite": True}
        init_response = requests.put("http://" + self.parsed_uri.uri_path, params=payload, allow_redirects=False)
        if not init_response.status_code == httplib.TEMPORARY_REDIRECT:
            raise WebHdfsException(str(init_response.status_code) + "\n" + init_response.content)
        uri = init_response.headers['location']
        response = requests.put(uri, data="", headers={'content-type': 'application/octet-stream'})
        if not response.status_code == httplib.CREATED:
            raise WebHdfsException(str(response.status_code) + "\n" + response.content)
        self.lines = []
        self.parts = 0
        self.chunk_bytes = 0
        self.total_size = 0

Example 3

Project: bunt Source File: recast.py
Function: update_bot
    def _update_bot(self):

        response = requests.put(
            url='{}'.format(self._url),
            json={
                'name': self._bot_slug,
                'strictness': self.strictness
            },
            headers=self._headers
        )
        return response

Example 4

Project: Kippt-for-Python Source File: lists.py
Function: update
    def update(self, **args):
        """ Updates a List.

        Parameters:
        - args Dictionary of other fields

        Accepted fields can be found here:
            https://github.com/kippt/api-docuementation/blob/master/objects/list.md
        """
        # JSONify our data.
        data = json.dumps(args)
        r = requests.put(
            "https://kippt.com/api/lists/%s" % (self.id),
            headers=self.kippt.header,
            data=data
        )
        return (r.json())

Example 5

Project: teuthology Source File: lock.py
Function: lock_one
def lock_one(name, user=None, description=None):
    name = misc.canonicalize_hostname(name, user=None)
    if user is None:
        user = misc.get_user()
    request = dict(name=name, locked=True, locked_by=user,
                   description=description)
    uri = os.path.join(config.lock_server, 'nodes', name, 'lock', '')
    response = requests.put(uri, json.dumps(request))
    success = response.ok
    if success:
        log.debug('locked %s as %s', name, user)
    else:
        try:
            reason = response.json().get('message')
        except ValueError:
            reason = str(response.status_code)
        log.error('failed to lock {node}. reason: {reason}'.format(
            node=name, reason=reason))
    return response

Example 6

Project: callsign Source File: client.py
Function: zone_add
    def zone_add(self, name):
        response = requests.put("%s/%s" % (self.base_url, name))
        if response.status_code != 201:
            self.handle_error(response, {
                409: "Domain data already exists. Delete first.",
                400: "Invalid request.",
                403: "Forbidden: domain is not allowed."
            })

Example 7

Project: st2 Source File: httpclient.py
Function: put
    @add_ssl_verify_to_kwargs
    @add_auth_token_to_headers
    @add_json_content_type_to_headers
    def put(self, url, data, **kwargs):
        response = requests.put(self.root + url, json.dumps(data), **kwargs)
        response = self._response_hook(response=response)
        return response

Example 8

Project: bit9platform Source File: bit9api.py
Function: update
    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)

Example 9

Project: synapsePythonClient Source File: multipart_upload.py
Function: put_chunk
def _put_chunk(url, chunk, verbose=False):
    response = requests.put(url, data=chunk)
    try:
        # Make sure requests closes response stream?:
        # see: http://docs.python-requests.org/en/latest/user/advanced/#keep-alive
        if response is not None:
            throw_away = response.content
    except Exception as ex:
        warnings.warn('error reading response: '+str(ex))
    exceptions._raise_for_status(response, verbose=verbose)

Example 10

Project: tile-generator Source File: opsmgr.py
Function: put_json
def put_json(url, payload):
	creds = get_credentials()
	url = creds.get('opsmgr').get('url') + url
	response = requests.put(url, auth=auth(creds), verify=False, json=payload)
	check_response(response)
	return response

Example 11

Project: nailgun Source File: client.py
Function: put
def put(url, data=None, **kwargs):
    """A wrapper for ``requests.put``. Sends a PUT request."""
    _set_content_type(kwargs)
    if _content_type_is_json(kwargs) and data is not None:
        data = dumps(data)
    _log_request('PUT', url, kwargs, data)
    response = requests.put(url, data, **kwargs)
    _log_response(response)
    return response

Example 12

Project: exocortex-halo Source File: web_index_bot.py
Function: send_message_to_user
def send_message_to_user(message):
    # Headers the XMPP bridge looks for for the message to be valid.
    headers = {'Content-type': 'application/json'}

    # Set up a hash table of stuff that is used to build the HTTP request to
    # the XMPP bridge.
    reply = {}
    reply['name'] = bot_name
    reply['reply'] = message

    # Send an HTTP request to the XMPP bridge containing the message for the
    # user.
    request = requests.put(server + "replies", headers=headers,
        data=json.dumps(reply))

Example 13

Project: mqtt2cloud Source File: Cosm.py
Function: push
    def push(self, feed, datastream, value):
        """
        Pushes a single value with current timestamp to the given feed/datastream
        """
        try:
            url = self.base_url % (feed, datastream) + ".json"
            data = json.dumps({'current_value' : value})
            response = requests.put(url, data=data, headers=self.headers(), timeout=self.timeout)
            self.last_response = response.status_code
            return self.last_response == 200
        except Exception as e:
            self.last_response = e
            return False

Example 14

Project: smap Source File: hue.py
Function: set_state
  def set_state(self, request, state):
    if self.api == "on":
      state = bool(state)
    payload = {self.api: state}
    r = requests.put("http://" + self.ip + "/api/"+self.user+"/lights/"+self.id+"/state",
        data=json.dumps(payload))
    return state

Example 15

Project: btb Source File: click2mail.py
    def upload_batch_xml(self, dry=False):
        url = "{}/{}".format(self.base_url, self.batch_id)
        print "PUT", url
        xml = self.build_batch_xml()
        if dry:
            print xml
        else:
            res = requests.put(url, data=xml,
                    headers={"Content-Type": "application/xml"},
                    auth=(self.username, self.password))
            results = self.check_res(res)

Example 16

Project: mortar-luigi Source File: mortar_recsys_api.py
    def _set_tables(self):
        headers = {'Accept': 'application/json',
                   'Accept-Encoding': 'gzip',
                   'Content-Type': 'application/json',
                   'User-Agent': 'mortar-luigi'}
        url = self._client_update_endpoint()
        body = {'ii_table': self.table_names()['ii_table'],
                'ui_table': self.table_names()['ui_table']}
        auth = HTTPBasicAuth(configuration.get_config().get('recsys', 'email'),
                             configuration.get_config().get('recsys', 'password'))
        logger.info('Setting new tables to %s at %s' % (body, url))
        response = requests.put(url, data=json.dumps(body), auth=auth, headers=headers)
        response.raise_for_status()

Example 17

Project: pyCiscoSpark Source File: pyCiscoSpark.py
def put_membership(at, membershipId, isModerator):
    headers = {'Authorization': _fix_at(at), 'content-type': 'application/json'}
    payload = {'isModerator': isModerator}
    resp = requests.put(url=_url('/memberships/{:s}'.format(membershipId)), json=payload, headers=headers)
    membership_dict = json.loads(resp.text)
    membership_dict['statuscode'] = str(resp.status_code)
    return membership_dict

Example 18

Project: python-requests-aws Source File: test.py
    def test_put_get_delete_cors(self):
        url = 'http://' + TEST_BUCKET + '.s3.amazonaws.com/?cors'
        testdata = '<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\
                            <CORSRule>\
                            <AllowedOrigin>*</AllowedOrigin>\
                            <AllowedMethod>POST</AllowedMethod>\
                            <MaxAgeSeconds>3000</MaxAgeSeconds>\
                            <AllowedHeader>Authorization</AllowedHeader>\
                        </CORSRule>\
                    </CORSConfiguration>'
        headers = {'content-md5': self.get_content_md5(testdata)}
        r = requests.put(url, data=testdata, auth=self.auth, headers=headers)
        self.assertEqual(r.status_code, 200)
        # Downloading current cors configuration
        r = requests.get(url, auth=self.auth)
        self.assertEqual(r.status_code, 200)
        # Removing removing cors configuration
        r = requests.delete(url, auth=self.auth)
        self.assertEqual(r.status_code, 204)

Example 19

Project: craftar-python Source File: _common.py
def _update_object_multipart(api_key, object_type, uuid, files, data):
    "Update a single object with an attachment (image file)"
    _validate(object_type=object_type, data=data, uuid=uuid)
    response = requests.put(
        url=_get_url(api_key, object_type, uuid),
        data=data,
        files=files,
    )
    _validate_response(response)
    return (response.status_code == 202)

Example 20

Project: python-mcollective Source File: rabbitmq.py
def nested_resource(resource, resource_key, nested_key, auth=AUTH, **kwargs):
    url = '{0}/api/{1}/{2}/{3}'.format(URL,
                                       resource,
                                       quote_plus(kwargs[resource_key]),
                                       quote_plus(kwargs[nested_key]))
    return requests.put(url,
                        auth=auth,
                        headers=HEADERS,
                        data=json.dumps(kwargs))

Example 21

Project: tile-generator Source File: opsmgr.py
Function: put
def put(url, payload, check=True):
	creds = get_credentials()
	url = creds.get('opsmgr').get('url') + url
	response = requests.put(url, auth=auth(creds), verify=False, data=payload)
	check_response(response, check=check)
	return response

Example 22

Project: grading-assigner Source File: grading-assigner.py
def refresh_request(current_request):
    logger.info('Refreshing existing request')
    refresh_resp = requests.put(REFRESH_URL_TMPL.format(BASE_URL, current_request['id']),
                                headers=headers)
    refresh_resp.raise_for_status()
    if refresh_resp.status_code == 404:
        logger.info('No active request was found/refreshed.  Loop and either wait for < 2 to be assigned or immediately create')
        return None
    else:
        return refresh_resp.json()

Example 23

Project: exocortex-halo Source File: paywall_breaker.py
Function: send_message_to_user
def send_message_to_user(message):
    logger.debug("Entered function send_message_to_message().")

    # Headers the XMPP bridge looks for for the message to be valid.
    headers = {'Content-type': 'application/json'}

    # Set up a hash table of stuff that is used to build the HTTP request to
    # the XMPP bridge.
    reply = {}
    reply['name'] = bot_name
    reply['reply'] = message

    # Send an HTTP request to the XMPP bridge containing the message for the
    # user.
    request = requests.put(server + "replies", headers=headers,
        data=json.dumps(reply))

Example 24

Project: ArrayServer Source File: client.py
    def __setitem__(self, name, array):
        """Stores the array in a memmap file, then pings server."""
        fn = tempfile.mktemp()
        fp = np.memmap(fn, dtype=array.dtype, mode='w+', shape=array.shape)
        fp[:] = array[:]
        
        requests.put(self.url(name), json.dumps({
            'dtype': str(array.dtype),
            'shape': list(array.shape),
            'filename': fn,
            }))

Example 25

Project: pyvcloud Source File: __init__.py
Function: put
    @staticmethod
    def put(url, data=None, logger=None, **kwargs):
        if logger is not None:
            Http._log_request(logger, data=data, headers=kwargs.get('headers', None))
        response = requests.put(url, data=data, **kwargs)
        Http._log_response(logger, response)
        return response

Example 26

Project: evohome-client Source File: __init__.py
Function: set_status
    def _set_status(self, status, until=None):
        self._populate_full_data()
        url = 'https://tccna.honeywell.com/WebAPI/api/evoTouchSystems?locationId=%s' % self.location_id
        if until is None:
            data = {"QuickAction":status,"QuickActionNextTime":None}
        else:
            data = {"QuickAction":status,"QuickActionNextTime":"%sT00:00:00Z" % until.strftime('%Y-%m-%d')}
        response = requests.put(url, data=json.dumps(data), headers=self.headers)
        
        task_id = self._get_task_id(response)
        
        while self._get_task_status(task_id) != 'Succeeded':
            time.sleep(1)

Example 27

Project: StrepHit Source File: post_job.py
def convert_gold(job_id):
    """
     Activate gold units in the given job.
     Corresponds to the 'Convert Uploaded Test Questions' UI button.

     :param str job_id: job ID registered in CrowdFlower
     :return: True on success
     :rtype: boolean
    """
    params = {'key': secrets.CF_KEY}
    r = requests.put(secrets.CF_JOB_ACTIVATE_GOLD_URL % job_id, params=params)
    log_request_data(r, logger)
    # Inconsistent API: returns 406, but actually sometimes works (!!!)
    if r.status_code == 406:
        return r.json()
    else:
        r.raise_for_status()

Example 28

Project: will Source File: hipchat.py
    def set_room_topic(self, room_id, topic):
        try:
            # https://www.hipchat.com/docs/apiv2/method/send_room_notification
            url = ROOM_TOPIC_URL % {"server": settings.HIPCHAT_SERVER,
                                    "room_id": room_id,
                                    "token": settings.V2_TOKEN}
            data = {
                "topic": topic,
            }
            headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
            requests.put(url, headers=headers, data=json.dumps(data), **settings.REQUESTS_OPTIONS)
        except:
            logging.critical("Error in set_room_topic: \n%s" % traceback.format_exc())

Example 29

Project: mqtt2cloud Source File: Xively.py
Function: push
    def push(self, feed, datastream, value):
        """
        Pushes a single value with current timestamp to the given feed/datastream
        """
        try:
            url = self.base_url % (feed, datastream)
            data = json.dumps({'current_value' : value})
            response = requests.put(url, data=data, headers=self.headers(), timeout=self.timeout)
            self.last_response = response.status_code
            return self.last_response == 200
        except Exception as e:
            self.last_response = e
            return False

Example 30

Project: sensorReporter Source File: restConn.py
Function: publish
    def publish(self, message, destination):
        """Called by others to publish a message to a Destination"""

        try:
            msg = "Published message '%s' to '%s'" % (message, destination)
            if debug:
                print msg
            requests.put(self.url + destination + "/state/",data=message)
            self.logger.info(msg)
        except:
            msg = "Unexpected error publishing message: %s" % (sys.exc_info()[0])
            print msg
            self.logger.error(msg)

Example 31

Project: callsign Source File: client.py
Function: record_a
    def record_a(self, zone, host, ip, ttl):
        url = "%s/%s" % (self.base_url, zone)
        payload = {host: {'type': 'A', 'address': ip}}
        if ttl:
            payload[host]['ttl'] = ttl
        headers = {'content-type': 'application/json'}
        response = requests.put(url, data=json.dumps(payload), headers=headers)
        if response.status_code != 201:
            self.handle_error(response, {
                404: "Error: Zone %r is not managed by callsign" % zone,
                400: response.reason
            })

Example 32

Project: pygerrit Source File: __init__.py
Function: put
    def put(self, endpoint, **kwargs):
        """ Send HTTP PUT to the endpoint.

        :arg str endpoint: The endpoint to send to.

        :returns:
            JSON decoded result.

        :raises:
            requests.RequestException on timeout or connection error.

        """
        kwargs.update(self.kwargs.copy())
        if "data" in kwargs:
            kwargs["headers"].update(
                {"Content-Type": "application/json;charset=UTF-8"})
        response = requests.put(self.make_url(endpoint), **kwargs)
        return _decode_response(response)

Example 33

Project: btb Source File: click2mail.py
    def upload_pdf(self, dry=False):
        with open(self.filename, 'rb') as fh:
            pdf = fh.read()
        url = "{}/{}".format(self.base_url, self.batch_id)
        print "PUT", url
        if dry:
            print "<%s bytes binary pdf data>" % len(pdf)
        else:
            res = requests.put(url, data=pdf,
                    headers={"Content-Type": "application/pdf"},
                    auth=(self.username, self.password))
            results = self.check_res(res)

Example 34

Project: pyrdm Source File: zenodo.py
Function: sort_files
   def sort_files(self, deposition_id, file_ids):
      """ Sorts a list of files (with their file_ids in a list called 'file_ids') associated with a given deposition_id on Zenodo. """

      url = self.api_url + "deposit/depositions/%d/files" % deposition_id
      url = self._append_suffix(url)

      headers = {"content-type": "application/json"}
      data = []
      for file_id in file_ids:
         data.append({"id":file_id})

      response = requests.put(url, data=json.dumps(data), headers=headers)
      results = json.loads(response.content)
      return results

Example 35

Project: FeedlyClient Source File: client.py
    def save_for_later(self, access_token, user_id, entryIds):
        '''saved for later.entryIds is a list for entry id.'''
        headers = {'content-type': 'application/json',
                   'Authorization': 'OAuth ' + access_token
        }
        request_url = self._get_endpoint('v3/tags') + '/user%2F' + user_id + '%2Ftag%2Fglobal.saved'
        
        params = dict(
                      entryIds=entryIds
                      )
        res = requests.put(url=request_url, data=json.dumps(params), headers=headers)
        return res  	

Example 36

Project: python-requests-aws Source File: test.py
    def test_put_get_delete(self):
        url = 'http://' + TEST_BUCKET + '.s3.amazonaws.com/myfile.txt'
        testdata = 'Sam is sweet'
        r = requests.put(url, data=testdata, auth=self.auth)
        self.assertEqual(r.status_code, 200)
        # Downloading a file
        r = requests.get(url, auth=self.auth)
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.text, 'Sam is sweet')
        # Removing a file
        r = requests.delete(url, auth=self.auth)
        self.assertEqual(r.status_code, 204)

Example 37

Project: pyCiscoSpark Source File: pyCiscoSpark.py
def put_webhook(at, webhookId, name, targetUrl):
    headers = {'Authorization': _fix_at(at), 'content-type': 'application/json'}
    payload = {'name': name, 'targetUrl': targetUrl}
    resp = requests.put(url=_url('/webhooks/{:s}'.format(webhookId)),json=payload, headers=headers)
    webhook_dict = json.loads(resp.text)
    webhook_dict['statuscode'] = str(resp.status_code)
    return webhook_dict

Example 38

Project: runbook Source File: cloudflare.py
Function: update_rec
def update_rec(email, key, zoneid, logger, recid, rec):
    ''' Update DNS record '''
    headers = {
        'X-Auth-Email' : email,
        'X-Auth-Key' : key,
        'Content-Type' : 'application/json'
    }
    url = "%s/zones/%s/dns_records/%s" % (baseurl, str(zoneid), str(recid))
    payload = json.dumps(rec)
    try:
        req = requests.put(url=url, headers=headers, data=payload)
        return validate_response(req, logger)
    except:
        return False

Example 39

Project: craftar-python Source File: _common.py
Function: update_object
def _update_object(api_key, object_type, uuid, data):
    "Update a single object"
    _validate(object_type=object_type, data=data, uuid=uuid)
    response = requests.put(
        url=_get_url(api_key, object_type, uuid),
        data=json.dumps(data),
        headers=HEADERS,
    )
    _validate_response(response)
    return (response.status_code == 202)

Example 40

Project: Kippt-for-Python Source File: clips.py
Function: update
    def update(self, **args):
        """ Updates a Clip.

        Parameters:
        - args Dictionary of other fields

        Accepted fields can be found here:
            https://github.com/kippt/api-docuementation/blob/master/objects/clip.md
        """
        # JSONify our data.
        data = json.dumps(args)
        r = requests.put(
            "https://kippt.com/api/clips/%s" % (self.id),
            headers=self.kippt.header,
            data=data)
        return (r.json())

Example 41

Project: osf.io Source File: utils.py
def upload_attachment(user, node, attachment):
    attachment.seek(0)
    name = '/' + (attachment.filename or settings.MISSING_FILE_NAME)
    content = attachment.read()
    upload_url = util.waterbutler_url_for('upload', 'osfstorage', name, node, user=user)

    requests.put(
        upload_url,
        data=content,
    )

Example 42

Project: evohome-client Source File: __init__.py
    def _set_heat_setpoint(self, zone, data):
        self._populate_full_data()
        
        device_id = self._get_device_id(zone)
        
        url = 'https://tccna.honeywell.com/WebAPI/api/devices/%s/thermostat/changeableValues/heatSetpoint' % device_id
        response = requests.put(url, json.dumps(data), headers=self.headers)

        task_id = self._get_task_id(response)
        
        while self._get_task_status(task_id) != 'Succeeded':
            time.sleep(1)

Example 43

Project: teuthology Source File: lock.py
Function: update_lock
def update_lock(name, description=None, status=None, ssh_pub_key=None):
    name = misc.canonicalize_hostname(name, user=None)
    updated = {}
    if description is not None:
        updated['description'] = description
    if status is not None:
        updated['up'] = (status == 'up')
    if ssh_pub_key is not None:
        updated['ssh_pub_key'] = ssh_pub_key

    if updated:
        uri = os.path.join(config.lock_server, 'nodes', name, '')
        response = requests.put(
            uri,
            json.dumps(updated))
        return response.ok
    return True

Example 44

Project: cabu Source File: bucket.py
    def put(self, filename, data):
        """Put given datas in the file with the given filename in the S3 bucket.

        Args:
            filename (str): A string representing the name of the file to store.
            datas (str|object): The datas to export.
        Returns:
            response (object): The object returned by requests.
        """
        url = 'http://' + self.bucket + '.s3.amazonaws.com/' + filename
        return requests.put(url, data=data, auth=S3Auth(self.access_key, self.secret_key))

Example 45

Project: threatshell Source File: passivetotal.py
Function: set_tags
    def set_tags(self, params):
        resp = requests.put(
            self.action_tags,
            auth=self.auth,
            data=json.dumps(params),
            headers=self.post_headers
        )

        if resp.status_code != requests.codes.ok:
            return self._error(
                "PUT",
                self.action_tags,
                resp.status_code,
                resp.content
            )

        return {"PUT": resp.json()}

Example 46

Project: zipa Source File: resource.py
Function: put
    def put(self, **kwargs):
        data = self._prepare_data(**kwargs)
        headers = {'content-type': 'application/json'}
        response = requests.put(self.url, data=data,
                                auth=self.config['auth'],
                                verify=self.config['verify'],
                                headers=headers)

        entity = self._prepare_entity(response)
        return entity

Example 47

Project: pyrdm Source File: zenodo.py
   def update_deposition(self, deposition_id):
      """ Update the metadata of a deposition with a given ID (deposition_id). """

      url = self.api_url + "deposit/depositions/%d" % deposition_id
      url = self._append_suffix(url)

      headers = {"content-type": "application/json"}
      data = {"metadata": {"title": title, "description": description, "upload_type": upload_type, "state": state}}

      response = requests.put(url, data=json.dumps(data), headers=headers)
      results = json.loads(response.content)
      return results

Example 48

Project: gremlinsdk-python Source File: failuregenerator.py
    def start_new_test(self):
        self._id = uuid.uuid4().hex
        for service in self.app.get_services():
            if self.debug:
                print(service)
            for instance in self.app.get_service_instances(service):
                resp = requests.put("http://{}/gremlin/v1/test/{}".format(instance,self._id))
                resp.raise_for_status()
        return self._id

Example 49

Project: django-page-cms Source File: pages_push.py
Function: push_content
    def push_content(self, page, desc):
        page_id = str(page['id'])
        auth = self.auth
        headers = {'Content-Type': 'application/json'}
        for content in tqdm(page['content_set'], leave=True, desc=desc):
            content['page'] = page_id
            data = json.dumps(content)
            url = self.host + 'contents/' + str(content['id']) + '/'
            response = requests.put(url, data=data, auth=self.auth, headers=headers)
            if response.status_code == 404:
                url = self.host + 'contents/'
                response = requests.post(url, data=data, auth=self.auth, headers=headers)
            if response.status_code != 200 and response.status_code != 201:
                self.http_error(response)

Example 50

Project: webrecorder Source File: uploadcontroller.py
Function: do_upload
    def do_upload(self, stream, user, coll, rec, offset, length):
        stream.seek(offset)

        stream = LimitReader(stream, length)
        headers = {'Content-Length': str(length)}

        upload_url = self.upload_path.format(record_host=self.record_host,
                                             user=user,
                                             coll=coll,
                                             rec=rec)

        r = requests.put(upload_url,
                         headers=headers,
                         data=stream)
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4