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 | 10 votes |
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 |
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: unicorn_binance_websocket_api_restclient.py From unicorn-binance-websocket-api with MIT License | 6 votes |
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
Source File: happn.py From happn with MIT License | 6 votes |
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 #5
Source File: firebase.py From pyfirebase with MIT License | 6 votes |
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 #6
Source File: projectdb.py From pyspider with Apache License 2.0 | 6 votes |
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 #7
Source File: happn.py From happn with MIT License | 6 votes |
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 #8
Source File: custom_resource.py From aws-ops-automator with Apache License 2.0 | 6 votes |
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 #9
Source File: teams_file_bot.py From botbuilder-python with MIT License | 6 votes |
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 #10
Source File: projectdb.py From pyspider with Apache License 2.0 | 6 votes |
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 #11
Source File: couchdbbase.py From pyspider with Apache License 2.0 | 6 votes |
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 #12
Source File: couchdbbase.py From pyspider with Apache License 2.0 | 6 votes |
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 #13
Source File: test_run.py From pyspider with Apache License 2.0 | 6 votes |
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 #14
Source File: test_run.py From pyspider with Apache License 2.0 | 6 votes |
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 #15
Source File: __init__.py From evohome-client with Apache License 2.0 | 6 votes |
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 #16
Source File: zone.py From evohome-client with Apache License 2.0 | 6 votes |
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 #17
Source File: helper.py From hsds with Apache License 2.0 | 6 votes |
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 #18
Source File: controlsystem.py From evohome-client with Apache License 2.0 | 6 votes |
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 #19
Source File: __init__.py From pyspider with Apache License 2.0 | 5 votes |
def _connect_couchdb(parsed, dbtype, url): if os.environ.get('COUCHDB_HTTPS'): url = "https://" + parsed.netloc + "/" else: url = "http://" + parsed.netloc + "/" params = {} # default to env, then url, then hard coded params['username'] = os.environ.get('COUCHDB_USER') or parsed.username or 'user' params['password'] = os.environ.get('COUCHDB_PASSWORD') or parsed.password or 'password' # create necessary DBs + the admin user res = requests.put(url + "_users") if 'error' in res and res['error'] == 'unauthorized': # user is already created. This will happen if CouchDB is running in docker # and COUCHDB_USER and COUCHDB_PASSWORD are set from requests.auth import HTTPBasicAuth requests.put(url + "_users", auth=HTTPBasicAuth(params['username'], params['password'])) requests.put(url + "_replicator", auth=HTTPBasicAuth(params['username'], params['password'])) requests.put(url + '_node/_local/_config/admins/' + params['username'], data=params['password'], auth=HTTPBasicAuth(params['username'], params['password'])) else: requests.put(url + "_replicator") requests.put(url + '_node/_local/_config/admins/' + params['username'], data=params['password']) if dbtype == 'taskdb': from .couchdb.taskdb import TaskDB return TaskDB(url, **params) elif dbtype == 'projectdb': from .couchdb.projectdb import ProjectDB return ProjectDB(url, **params) elif dbtype == 'resultdb': from .couchdb.resultdb import ResultDB return ResultDB(url, **params) else: raise LookupError
Example #20
Source File: test_database.py From pyspider with Apache License 2.0 | 5 votes |
def setUpClass(self): # create a test admin user import requests requests.put('http://localhost:5984/_node/_local/_config/admins/test', data='"password"') os.environ["COUCHDB_USER"] = "test" os.environ["COUCHDB_PASSWORD"] = "password" self.projectdb = database.connect_database( 'couchdb+projectdb://localhost:5984/' ) self.assertIsNotNone(self, self.projectdb)
Example #21
Source File: test_database.py From pyspider with Apache License 2.0 | 5 votes |
def setUpClass(self): # create a test admin user import requests requests.put('http://localhost:5984/_node/_local/_config/admins/test', data='"password"') os.environ["COUCHDB_USER"] = "test" os.environ["COUCHDB_PASSWORD"] = "password" self.resultdb = database.connect_database( 'couchdb+resultdb://localhost:5984/' ) self.assertIsNotNone(self, self.resultdb)
Example #22
Source File: test_database.py From pyspider with Apache License 2.0 | 5 votes |
def setUpClass(self): # create a test admin user import requests requests.put('http://localhost:5984/_node/_local/_config/admins/test', data='"password"') os.environ["COUCHDB_USER"] = "test" os.environ["COUCHDB_PASSWORD"] = "password" self.taskdb = database.connect_database( 'couchdb+taskdb://localhost:5984/' ) self.assertIsNotNone(self, self.taskdb)
Example #23
Source File: happn.py From happn with MIT License | 5 votes |
def set_matching_age_min(self, age): """ Set matching min. age :mininum age to like """ # 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 = { 'matching_age_min' : age } url = 'https://api.happn.fr/api/users/' + self.id try: r = requests.put(url, headers=h, data = payload,verify=False) except Exception as e: raise HTTP_MethodError('Error Connecting to Happn Server: {}'.format(e)) if r.status_code == 200: #200 = 'OK' logging.debug('Set minimum accept age to '+str(age)) else: # Unable to fetch distance raise HTTP_MethodError(httpErrors[r.status_code])
Example #24
Source File: domain_test.py From hsds with Apache License 2.0 | 5 votes |
def testInvalidChildDomain(self): domain = self.base_domain + "/notafolder/newdomain.h5" # should fail assuming "notafolder" doesn't exist headers = helper.getRequestHeaders(domain=domain) req = helper.getEndpoint() + '/' rsp = requests.put(req, headers=headers) self.assertEqual(rsp.status_code, 404)
Example #25
Source File: domain_test.py From hsds with Apache License 2.0 | 5 votes |
def testCreateFolder(self): domain = self.base_domain + "/newfolder" print("testCreateFolder", domain) headers = helper.getRequestHeaders(domain=domain) req = helper.getEndpoint() + '/' body = {"folder": True} rsp = requests.put(req, data=json.dumps(body), headers=headers) self.assertEqual(rsp.status_code, 201) rspJson = json.loads(rsp.text) for k in ("owner", "acls", "created", "lastModified"): self.assertTrue(k in rspJson) self.assertFalse("root" in rspJson) # no root -> folder # verify that putting the same domain again fails with a 409 error rsp = requests.put(req, data=json.dumps(body), headers=headers) self.assertEqual(rsp.status_code, 409) # do a get on the new folder rsp = requests.get(req, headers=headers) self.assertEqual(rsp.status_code, 200) rspJson = json.loads(rsp.text) self.assertTrue("owner" in rspJson) self.assertTrue("class" in rspJson) self.assertEqual(rspJson["class"], "folder") # try doing a un-authenticated request if config.get("test_noauth") and config.get("default_public"): headers = helper.getRequestHeaders() req = helper.getEndpoint() + "/?host=" + domain # do a get on the folder with a query arg for host rsp = requests.get(req) self.assertEqual(rsp.status_code, 200) rspJson = json.loads(rsp.text) for k in ("class", "owner"): self.assertTrue(k in rspJson) self.assertFalse("root" in rspJson)
Example #26
Source File: attr_test.py From hsds with Apache License 2.0 | 5 votes |
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)
Example #27
Source File: happn.py From happn with MIT License | 5 votes |
def set_matching_age_max(self, age): """ Set matching max. age :maximum age to like """ # 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 = { 'matching_age_max' : age } url = 'https://api.happn.fr/api/users/' + self.id try: r = requests.put(url, headers=h, data = payload,verify=False) except Exception as e: raise HTTP_MethodError('Error Connecting to Happn Server: {}'.format(e)) if r.status_code == 200: #200 = 'OK' logging.debug('Set maximum accept age to '+str(age)) else: # Unable to fetch distance raise HTTP_MethodError(httpErrors[r.status_code])
Example #28
Source File: attr_test.py From hsds with Apache License 2.0 | 5 votes |
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 #29
Source File: attr_test.py From hsds with Apache License 2.0 | 5 votes |
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 #30
Source File: channel.py From CyberTK-Self with GNU General Public License v2.0 | 5 votes |
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()