Python requests.org() Examples

The following are 30 code examples for showing how to use requests.org(). 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: Wikipedia-API   Author: martin-majlis   File: __init__.py    License: MIT License 6 votes vote down vote up
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 2
Project: chinese-support-redux   Author: luoliyan   File: tts.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 3
Project: pytgbot   Author: luckydonald   File: files.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 4
Project: python-sample-auth   Author: microsoftgraph   File: graphrest.py    License: MIT License 6 votes vote down vote up
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 5
Project: python-sample-auth   Author: microsoftgraph   File: graphrest.py    License: MIT License 6 votes vote down vote up
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 6
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 7
Project: python-sample-auth   Author: microsoftgraph   File: graphrest.py    License: MIT License 6 votes vote down vote up
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 8
Project: python-sample-auth   Author: microsoftgraph   File: graphrest.py    License: MIT License 6 votes vote down vote up
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 9
Project: python-devicecloud   Author: digidotcom   File: __init__.py    License: Mozilla Public License 2.0 6 votes vote down vote up
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 10
Project: python-devicecloud   Author: digidotcom   File: __init__.py    License: Mozilla Public License 2.0 6 votes vote down vote up
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 11
Project: python-devicecloud   Author: digidotcom   File: __init__.py    License: Mozilla Public License 2.0 6 votes vote down vote up
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 12
Project: python-devicecloud   Author: digidotcom   File: __init__.py    License: Mozilla Public License 2.0 6 votes vote down vote up
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 13
Project: snippet   Author: xgfone   File: utils.py    License: MIT License 6 votes vote down vote up
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 14
Project: rssant   Author: anyant   File: reader.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 15
Project: dropbox-sdk-python   Author: dropbox   File: dropbox.py    License: MIT License 6 votes vote down vote up
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 16
Project: exbert   Author: bhoov   File: hf_api.py    License: Apache License 2.0 6 votes vote down vote up
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 17
Project: automation-scripts   Author: meraki   File: manageadmins.py    License: MIT License 6 votes vote down vote up
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 18
Project: automation-scripts   Author: meraki   File: migrate_cat3k.py    License: MIT License 6 votes vote down vote up
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 19
Project: automation-scripts   Author: meraki   File: provision_sites.py    License: MIT License 6 votes vote down vote up
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 20
Project: automation-scripts   Author: meraki   File: cloneprovision.py    License: MIT License 6 votes vote down vote up
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 21
Project: automation-scripts   Author: meraki   File: deviceupdownstatus.py    License: MIT License 6 votes vote down vote up
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 22
Project: automation-scripts   Author: meraki   File: deviceupdownstatus.py    License: MIT License 6 votes vote down vote up
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 23
Project: automation-scripts   Author: meraki   File: clientcount.py    License: MIT License 6 votes vote down vote up
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 24
Project: automation-scripts   Author: meraki   File: addroutes.py    License: MIT License 6 votes vote down vote up
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 25
Project: automation-scripts   Author: meraki   File: topusers.py    License: MIT License 6 votes vote down vote up
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 26
Project: automation-scripts   Author: meraki   File: topusers.py    License: MIT License 6 votes vote down vote up
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 27
Project: onedrive-sdk-python   Author: OneDrive   File: http_provider_with_proxy.py    License: MIT License 6 votes vote down vote up
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 28
Project: controller   Author: deis   File: __init__.py    License: MIT License 5 votes vote down vote up
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 29
Project: seqr   Author: macarthur-lab   File: staff_api.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def proxy_to_kibana(request):
    headers = _convert_django_meta_to_http_headers(request.META)
    headers['Host'] = KIBANA_SERVER

    url = "{scheme}://{host}{path}".format(scheme=request.scheme, host=KIBANA_SERVER, path=request.get_full_path())

    request_method = getattr(requests.Session(), request.method.lower())

    try:
        # use stream=True because kibana returns gziped responses, and this prevents the requests module from
        # automatically unziping them
        response = request_method(url, headers=headers, data=request.body, stream=True, verify=True)
        response_content = response.raw.read()
        # make sure the connection is released back to the connection pool
        # (based on http://docs.python-requests.org/en/master/user/advanced/#body-content-workflow)
        response.close()

        proxy_response = HttpResponse(
            content=response_content,
            status=response.status_code,
            reason=response.reason,
            charset=response.encoding
        )

        for key, value in response.headers.iteritems():
            if key.lower() not in EXCLUDE_HTTP_RESPONSE_HEADERS:
                proxy_response[key.title()] = value

        return proxy_response
    except ConnectionError as e:
        logger.error(e)
        return HttpResponse("Error: Unable to connect to Kibana {}".format(e), status=400) 
Example 30
Project: redditDataExtractor   Author: NSchrading   File: redditDataExtractorGUI.py    License: GNU General Public License v3.0 5 votes vote down vote up
def displayAbout(self):
        msgBox = QMessageBox()
        msgBox.setTextFormat(Qt.RichText)
        msgBox.setWindowTitle("Data Extractor for reddit")
        msgBox.setText("""
            <p>This program uses the following open source software:<br>
            <a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro">PyQt</a> under the GNU GPL v3 license
            <br>
            <a href="https://praw.readthedocs.org/en/v2.1.16/">PRAW (Python Reddit API Wrapper)</a> under the GNU GPL v3 license
            <br>
            <a href="http://docs.python-requests.org/en/latest/">Requests</a> under the Apache2 license
            <br>
            <a href="http://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> under a simplified BSD licence
            <br>
            <a href="https://github.com/rg3/youtube-dl">youtube-dl</a> under an unlicense (public domain)
            </p>

            <p>This program makes use of a modified version of <a href="https://www.videolan.org/vlc/">VLC's</a> logo:<br>
            Copyright (c) 1996-2013 VideoLAN. This logo or a modified version may<br>
            be used or modified by anyone to refer to the VideoLAN project or any<br>
            product developed by the VideoLAN team, but does not indicate<br>
            endorsement by the project.
            </p>

            <p>This program makes use of a modified version of Microsoft Window's<br>
            .txt file icon. This is solely the property of Microsoft Windows<br>
            and I claim no ownership.
            </p>

            <p>This program is released under the GNU GPL v3 license<br>
            <a href="https://www.gnu.org/licenses/quick-guide-gplv3.html">GNU GPL v3 license page</a><br>
            See <a href="https://github.com/NSchrading/redditDataExtractor/blob/master/LICENSE.txt">LICENSE.txt</a> for more information.
            </p>
        """)
        msgBox.exec()