Python requests.org() Examples
The following are 30
code examples of requests.org().
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: dropbox.py From dropbox-sdk-python with MIT License | 6 votes |
def create_session(max_connections=8, proxies=None): """ Creates a session object that can be used by multiple :class:`Dropbox` and :class:`DropboxTeam` instances. This lets you share a connection pool amongst them, as well as proxy parameters. :param int max_connections: Maximum connection pool size. :param dict proxies: See the `requests module <http://docs.python-requests.org/en/latest/user/advanced/#proxies>`_ for more details. :rtype: :class:`requests.sessions.Session`. `See the requests module <http://docs.python-requests.org/en/latest/user/advanced/#session-objects>`_ for more details. """ # We only need as many pool_connections as we have unique hostnames. session = pinned_session(pool_maxsize=max_connections) if proxies: session.proxies = proxies return session
Example #2
Source File: deviceupdownstatus.py From automation-scripts with MIT License | 6 votes |
def printhelp(): #prints help text printusertext('This is a script to print a list of all devices in a organization\'s inventory and their up/down status.') printusertext(' The script will not return up/down status for MV security cameras, as this was not supported at time of writing.') printusertext('') printusertext('To run the script, enter:') printusertext(' python deviceupdownstatus.py -k <api key> -o <org name> [-a <snmp auth key> -p <snmp priv key>]') printusertext('') printusertext('Mandatory argument:s') printusertext(' -k <key> : Your Meraki Dashboard API key') printusertext(' -o <org name> : Your Dashboard Organization name') printusertext('Optional arguments to use SNMPv3:') printusertext(' -a <snmp auth key> : SNMPv3 authentication key. Required for SNMPv3') printusertext(' -p <snmp priv key> : SNMPv3 privacy key. Required for SNMPv3') printusertext('') printusertext('Example:') printusertext(' python deviceupdownstatus.py -k 1234 -o "Meraki Inc" -a authpass123 -p privpass123') printusertext('') printusertext('Use double quotes ("") in Windows to pass arguments containing spaces. Names are case-sensitive.')
Example #3
Source File: __init__.py From Wikipedia-API with MIT License | 6 votes |
def _query( self, page: 'WikipediaPage', params: Dict[str, Any] ): base_url = 'https://' + page.language + '.wikipedia.org/w/api.php' log.info( "Request URL: %s", base_url + "?" + "&".join( [k + "=" + str(v) for k, v in params.items()] ) ) params['format'] = 'json' params['redirects'] = 1 r = self._session.get( base_url, params=params, **self._request_kwargs ) return r.json()
Example #4
Source File: cloneprovision.py From automation-scripts with MIT License | 6 votes |
def updateVlan(p_apiKey, p_shard, p_netId, p_vlanId, p_vlanSubnet, p_mxIp): #updates an existing MX VLAN in the specified org merakiRequestThrottler() payload = json.dumps({'applianceIp': p_mxIp, 'subnet': p_vlanSubnet}) try: r = requests.put('https://%s/api/v0/networks/%s/vlans/%s' % (p_shard, p_netId, p_vlanId), data=payload, headers={'X-Cisco-Meraki-API-Key': p_apiKey, 'Content-Type': 'application/json'}, timeout=(REQUESTS_CONNECT_TIMEOUT, REQUESTS_READ_TIMEOUT)) except: return None if 200 <= r.status_code < 300: return 'success' return None #SECTION: main
Example #5
Source File: deviceupdownstatus.py From automation-scripts with MIT License | 6 votes |
def getorgid(p_apikey, p_orgname): #looks up org id for a specific org name #on failure returns 'null' merakirequestthrottler() try: r = requests.get('https://api.meraki.com/api/v0/organizations', headers={'X-Cisco-Meraki-API-Key': p_apikey, 'Content-Type': 'application/json'}) except: printusertext('ERROR 07: Unable to contact Meraki cloud') sys.exit(2) if r.status_code != requests.codes.ok: return 'null' rjson = r.json() for record in rjson: if record['name'] == p_orgname: return record['id'] return('null')
Example #6
Source File: addroutes.py From automation-scripts with MIT License | 6 votes |
def getOrgId(p_apiKey, p_orgName): #returns the organizations' list for a specified admin, with filters applied merakiRequestThrottler() try: r = requests.get('https://api.meraki.com/api/v0/organizations', headers={'X-Cisco-Meraki-API-Key': p_apiKey, 'Content-Type': 'application/json'}, timeout=(REQUESTS_CONNECT_TIMEOUT, REQUESTS_READ_TIMEOUT) ) except: return(None) if r.status_code != requests.codes.ok: return(None) rjson = r.json() for org in rjson: if org['name'] == p_orgName: return org['id'] return(None)
Example #7
Source File: provision_sites.py From automation-scripts with MIT License | 6 votes |
def getOrgId(p_apiKey, p_orgName): #returns the organizations' list for a specified admin, with filters applied merakiRequestThrottler() try: r = requests.get( API_BASE_URL + '/organizations', headers={'X-Cisco-Meraki-API-Key': p_apiKey, 'Content-Type': 'application/json'}, timeout=(REQUESTS_CONNECT_TIMEOUT, REQUESTS_READ_TIMEOUT) ) except: return None if r.status_code != requests.codes.ok: return None rjson = r.json() for org in rjson: if org['name'] == p_orgName: return org['id'] return None
Example #8
Source File: topusers.py From automation-scripts with MIT License | 6 votes |
def printhelp(): print('This is a Python 3 script to get the top 10 heaviest bandwidth users of an MX security appliance for') print(' the last 10, 30 and 60 minutes. The script creates a web interface, which can be accessed with a web') print(' browser via HTTP or HTTPS.') print('') print('Usage:') print(' python topusers.py -k <api key> [-o <org name>] [-m <mode>]') print('') print('Command line parameters:') print(' -k <api key> : Your Meraki Dashboard API key. The key needs to have at least org-wide read access.') print(' -o <org name>: Optional. Use this to pull the networks list only from a specific organization.') print(' -m <mode> : Optional. Defines server security level. Either "http" or "https". Default is "https".') print('') print('Example:') print(' python topusers.py -k 1234 -o "Big Industries Inc"') print('') print('Notes:') print(' * In Windows, use double quotes ("") to enter command line parameters containing spaces.') #SECTION: Meraki Dashboard API communication functions
Example #9
Source File: http_provider_with_proxy.py From onedrive-sdk-python with MIT License | 6 votes |
def __init__(self, proxies=None, verify_ssl=True): """Initializes the provider. Proxy and SSL settings are stored in the object and applied to every request. Args: proxies (dict of str:str): Mapping of protocols to proxy URLs. See `requests` documentation: http://docs.python-requests.org/en/latest/api/#requests.request If None, HttpProviderWithProxy.DEFAULT_PROXIES is used. verify_ssl (bool): Whether SSL certs should be verified during request proxy. """ self.proxies = proxies if proxies is not None \ else HttpProviderWithProxy.DEFAULT_PROXIES self.verify_ssl = verify_ssl
Example #10
Source File: topusers.py From automation-scripts with MIT License | 6 votes |
def index(): form = c_NetSelectForm() output = None form.netname.choices = [] for org in ORG_LIST: for net in org.nets: form.netname.choices.append(('%s|%s|%s|%s|%s' % (org.id, org.shard, net.id, net.mxsn1, net.mxsn2), '%s [%s]' % (net.name, org.name) )) if request.method == 'POST': output = c_Output() netparams = form.netname.data.split('|') output.short = getUsageReport(netparams, TIMERANGE_SHORT_MINUTES) output.mid = getUsageReport(netparams, TIMERANGE_MEDIUM_MINUTES) output.long = getUsageReport(netparams, TIMERANGE_LONG_MINUTES) output.timestamp= str(datetime.datetime.now()) return render_template('index.html', form=form, tshort=TIMERANGE_SHORT_MINUTES, tmid=TIMERANGE_MEDIUM_MINUTES, tlong=TIMERANGE_LONG_MINUTES, output=output)
Example #11
Source File: clientcount.py From automation-scripts with MIT License | 6 votes |
def printhelp(): print('This is a Python 3 script to count the total unique client MAC addresses connected to MR access points for') print(' an organization during the last month.') print('') print('Usage:') print(' clientcount.py -k <api key> [-o <org name>]') print('') print('Parameters:') print(' -k <api key> : Mandatory. Your Meraki Dashboard API key') print(' -o <org name> : Optional. Name of the organization you want to process. Use keyword "/all" to explicitly') print(' specify all orgs. Default is "/all"') print('') print('Example:') print(' clientcount.py -k 1234 -o "Big Industries Inc"') print('') print('Notes:') print(' * In Windows, use double quotes ("") to enter command line parameters containing spaces.') #SECTION: Meraki Dashboard API communication functions
Example #12
Source File: tts.py From chinese-support-redux with GNU General Public License v3.0 | 6 votes |
def infer_msg(self, tts, rsp): """Attempt to guess what went wrong by using known information (e.g. http response) and observed behaviour """ # rsp should be <requests.Response> # http://docs.python-requests.org/en/master/api/ status = rsp.status_code reason = rsp.reason cause = "Unknown" if status == 403: cause = "Bad token or upstream API changes" elif status == 404 and not tts.lang_check: cause = "Unsupported language '%s'" % self.tts.lang elif status >= 500: cause = "Uptream API error. Try again later." return "%i (%s) from TTS API. Probable cause: %s" % ( status, reason, cause)
Example #13
Source File: migrate_cat3k.py From automation-scripts with MIT License | 6 votes |
def getOrgId(p_apiKey, p_orgName): #returns the organizations' list for a specified admin, with filters applied merakiRequestThrottler() try: r = requests.get( API_BASE_URL + '/organizations', headers={'X-Cisco-Meraki-API-Key': p_apiKey, 'Content-Type': 'application/json'}, timeout=(REQUESTS_CONNECT_TIMEOUT, REQUESTS_READ_TIMEOUT) ) except: return None if r.status_code != requests.codes.ok: return None rjson = r.json() for org in rjson: if org['name'] == p_orgName: return org['id'] return None
Example #14
Source File: files.py From pytgbot with GNU General Public License v3.0 | 6 votes |
def get_request_files(self, var_name): """ Returns a dictionary containing attachments as `{var_name: ('foo.png', open('foo.png', 'rb'), 'image/png')}`. For the format of thoses tuples see the requests docs: http://docs.python-requests.org/en/master/user/advanced/#post-multiple-multipart-encoded-files Used by :py:func:`~pytgbot.bot.Bot._do_fileupload`. :param var_name: The variable name we want to send the file as. :type var_name: str :return: A dictionary, containing attachments how they are needed by the requests library. :rtype: dict """ raise NotImplementedError('Your sub-class should implement this.') # end def
Example #15
Source File: graphrest.py From python-sample-auth with MIT License | 6 votes |
def get(self, endpoint='me', *, headers=None, stream=False, verify=False, params=None): """Wrapper for authenticated HTTP GET 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 stream = Requests streaming option; set to True for image data, etc. 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() # Merge passed headers with default headers. merged_headers = self.headers() if headers: merged_headers.update(headers) return requests.get(self.api_endpoint(endpoint), headers=merged_headers, stream=stream, verify=verify, params=params)
Example #16
Source File: graphrest.py From python-sample-auth with MIT License | 6 votes |
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 #17
Source File: graphrest.py From python-sample-auth with MIT License | 6 votes |
def post(self, endpoint, headers=None, data=None, verify=False, params=None): """POST to API (authenticated with access token). headers = custom HTTP headers (merged with defaults, including access token) 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-cert-verification """ self.token_validation() merged_headers = self.headers() if headers: merged_headers.update(headers) return requests.post(self.api_endpoint(endpoint), headers=merged_headers, data=data, verify=verify, params=params)
Example #18
Source File: graphrest.py From python-sample-auth with MIT License | 6 votes |
def put(self, endpoint, *, headers=None, data=None, verify=False, params=None): """Wrapper for authenticated HTTP PUT 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.put(self.api_endpoint(endpoint), headers=self.headers(headers), data=data, verify=verify, params=params)
Example #19
Source File: manageadmins.py From automation-scripts with MIT License | 6 votes |
def cmdadd(p_apikey, p_orgs, p_email, p_name, p_privilege): #creates an administrator in all orgs in scope if p_privilege not in ['full', 'read-only']: printusertext('ERROR 09: Unsupported privilege level "%s"' % p_privilege) sys.exit(2) for org in p_orgs: orgadmins = getorgadmins(p_apikey, org, 'api.meraki.com') adminid = findadminid(orgadmins, p_email) if adminid != 'null': printusertext('INFO: Skipping org "%s". Admin already exists' % org.name) else: printusertext('INFO: Creating admin "%s" in org "%s"' % (p_email, org.name)) addorgadmin(p_apikey, org.id, 'api.meraki.com', p_email, p_name, p_privilege) #verify that admin was correctly created orgadmins = getorgadmins(p_apikey, org, 'api.meraki.com') adminid = findadminid(orgadmins, p_email) if adminid == 'null': printusertext('WARNING: Unable to create admin "%s" in org "%s"' % (p_email, org.name)) return(0)
Example #20
Source File: __init__.py From python-devicecloud with Mozilla Public License 2.0 | 6 votes |
def get(self, path, **kwargs): """Perform an HTTP GET request of the specified path in Device Cloud Make an HTTP GET request against Device Cloud with this accounts credentials and base url. This method uses the `requests <http://docs.python-requests.org/en/latest/>`_ library `request method <http://docs.python-requests.org/en/latest/api/#requests.request>`_ and all keyword arguments will be passed on to that method. :param str path: Device Cloud path to GET :param int retries: The number of times the request should be retried if an unsuccessful response is received. Most likely, you should leave this at 0. :raises DeviceCloudHttpException: if a non-success response to the request is received from Device Cloud :returns: A requests ``Response`` object """ url = self._make_url(path) return self._make_request("GET", url, **kwargs)
Example #21
Source File: __init__.py From python-devicecloud with Mozilla Public License 2.0 | 6 votes |
def post(self, path, data, **kwargs): """Perform an HTTP POST request of the specified path in Device Cloud Make an HTTP POST request against Device Cloud with this accounts credentials and base url. This method uses the `requests <http://docs.python-requests.org/en/latest/>`_ library `request method <http://docs.python-requests.org/en/latest/api/#requests.request>`_ and all keyword arguments will be passed on to that method. :param str path: Device Cloud path to POST :param int retries: The number of times the request should be retried if an unsuccessful response is received. Most likely, you should leave this at 0. :param data: The data to be posted in the body of the POST request (see docs for ``requests.post`` :raises DeviceCloudHttpException: if a non-success response to the request is received from Device Cloud :returns: A requests ``Response`` object """ url = self._make_url(path) return self._make_request("POST", url, data=data, **kwargs)
Example #22
Source File: __init__.py From python-devicecloud with Mozilla Public License 2.0 | 6 votes |
def put(self, path, data, **kwargs): """Perform an HTTP PUT request of the specified path in Device Cloud Make an HTTP PUT request against Device Cloud with this accounts credentials and base url. This method uses the `requests <http://docs.python-requests.org/en/latest/>`_ library `request method <http://docs.python-requests.org/en/latest/api/#requests.request>`_ and all keyword arguments will be passed on to that method. :param str path: Device Cloud path to PUT :param int retries: The number of times the request should be retried if an unsuccessful response is received. Most likely, you should leave this at 0. :param data: The data to be posted in the body of the POST request (see docs for ``requests.post`` :raises DeviceCloudHttpException: if a non-success response to the request is received from Device Cloud :returns: A requests ``Response`` object """ url = self._make_url(path) return self._make_request("PUT", url, data=data, **kwargs)
Example #23
Source File: __init__.py From python-devicecloud with Mozilla Public License 2.0 | 6 votes |
def delete(self, path, retries=DEFAULT_THROTTLE_RETRIES, **kwargs): """Perform an HTTP DELETE request of the specified path in Device Cloud Make an HTTP DELETE request against Device Cloud with this accounts credentials and base url. This method uses the `requests <http://docs.python-requests.org/en/latest/>`_ library `request method <http://docs.python-requests.org/en/latest/api/#requests.request>`_ and all keyword arguments will be passed on to that method. :param str path: Device Cloud path to DELETE :param int retries: The number of times the request should be retried if an unsuccessful response is received. Most likely, you should leave this at 0. :raises DeviceCloudHttpException: if a non-success response to the request is received from Device Cloud :returns: A requests ``Response`` object """ url = self._make_url(path) return self._make_request("DELETE", url, **kwargs)
Example #24
Source File: hf_api.py From exbert with Apache License 2.0 | 6 votes |
def presign_and_upload(self, token: str, filename: str, filepath: str) -> str: """ Get a presigned url, then upload file to S3. Outputs: url: Read-only url for the stored file on S3. """ urls = self.presign(token, filename=filename) # streaming upload: # https://2.python-requests.org/en/master/user/advanced/#streaming-uploads # # Even though we presign with the correct content-type, # the client still has to specify it when uploading the file. with open(filepath, "rb") as f: pf = TqdmProgressFileReader(f) data = f if pf.total_size > 0 else "" r = requests.put(urls.write, data=data, headers={"content-type": urls.type}) r.raise_for_status() pf.close() return urls.access
Example #25
Source File: utils.py From snippet with MIT License | 6 votes |
def send_http_json(method, url, exc=True, headers=None, **kwargs): """Send the HTTP request. See: http://www.python-requests.org/en/master/api/#requests.Session.request """ if headers: headers["Accept"] = "application/json" else: headers = {"Accept": "application/json"} resp = getattr(requests, method)(url, headers=headers, **kwargs) if exc: resp.raise_for_status() data = resp.content if resp.status_code == 200: if resp.content: data = resp.json() return resp.status_code, data
Example #26
Source File: reader.py From rssant with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _send_request(self, request, ignore_content): # http://docs.python-requests.org/en/master/user/advanced/#timeouts response = self.session.send(request, timeout=(6.5, self.request_timeout), stream=True) try: if not is_ok_status(response.status_code): content = self._read_content(response) return response, content self.check_content_type(response) content = None if not ignore_content: content = self._read_content(response) finally: # Fix: Requests memory leak # https://github.com/psf/requests/issues/4601 response.close() return response, content
Example #27
Source File: graphrest.py From python-sample-auth with MIT License | 6 votes |
def delete(self, endpoint, *, headers=None, data=None, verify=False, params=None): """Wrapper for authenticated HTTP DELETE 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.delete(self.api_endpoint(endpoint), headers=self.headers(headers), data=data, verify=verify, params=params)
Example #28
Source File: handler.py From permabots with BSD 3-Clause "New" or "Revised" License | 5 votes |
def process(self, **context): """ Process handler request. Before executing requests render templates with context :param context: Processing context :returns: Requests response `<http://docs.python-requests.org/en/master/api/#requests.Response>` _. """ env = Environment(extensions=['jinja2_time.TimeExtension']) url_template = env.from_string(self.url_template) url = url_template.render(**context).replace(" ", "") logger.debug("Request %s generates url %s" % (self, url)) params = self._url_params(**context) logger.debug("Request %s generates params %s" % (self, params)) headers = self._header_params(**context) logger.debug("Request %s generates header %s" % (self, headers)) if self.data_required(): data_template = env.from_string(self.data) data = data_template.render(**context) logger.debug("Request %s generates data %s" % (self, data)) r = self._get_method()(url, data=json.loads(data), headers=headers, params=params) else: r = self._get_method()(url, headers=headers, params=params) return r
Example #29
Source File: __init__.py From controller with MIT License | 5 votes |
def get_session(): global session if session is None: session = requests.Session() session.headers = { # https://toolbelt.readthedocs.org/en/latest/user-agent.html#user-agent-constructor 'User-Agent': user_agent('Deis Controller', deis_version), } # `mount` a custom adapter that retries failed connections for HTTP and HTTPS requests. # http://docs.python-requests.org/en/latest/api/#requests.adapters.HTTPAdapter session.mount('http://', requests.adapters.HTTPAdapter(max_retries=10)) session.mount('https://', requests.adapters.HTTPAdapter(max_retries=10)) return session
Example #30
Source File: clientesathub.py From satcfe with Apache License 2.0 | 5 votes |
def _http_post(self, metodo, **payload): if not _requests_disponivel: raise RuntimeError( 'Biblioteca \'requests\' [1] necessaria para invocar ' 'funcoes do equipamento SAT atraves de um cliente SATHub. ' '[1] https://python-requests.org/' ) if 'numero_caixa' not in payload: payload.update({'numero_caixa': self._numero_caixa}) headers = self._request_headers() resp = requests.post(self._url(metodo), data=payload, headers=headers) resp.raise_for_status() return resp