Python requests.compat() Examples

The following are code examples for showing how to use requests.compat(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: ares   Author: barnumbirr   File: core.py    Apache License 2.0 5 votes vote down vote up
def __request(self, endpoint, query):
		response_object = self.session.get(requests.compat.urljoin(self.base_url + endpoint, query),
		                                   timeout = self.request_timeout)

		try:
			response = json.loads(response_object.text)
		except Exception as e:
			return e

		return response 
Example 2
Project: filegardener   Author: smorin   File: test_requests.py    MIT License 5 votes vote down vote up
def test_unicode_header_name(self, httpbin):
        requests.put(
            httpbin('put'),
            headers={str('Content-Type'): 'application/octet-stream'},
            data='\xff')  # compat.str is unicode. 
Example 3
Project: filegardener   Author: smorin   File: test_requests.py    MIT License 5 votes vote down vote up
def test_unicode_header_name(self, httpbin):
        requests.put(
            httpbin('put'),
            headers={str('Content-Type'): 'application/octet-stream'},
            data='\xff')  # compat.str is unicode. 
Example 4
Project: SublimeBart   Author: ganemone   File: test_requests.py    MIT License 5 votes vote down vote up
def test_unicode_header_name(self):
        requests.put(
            httpbin('put'),
            headers={str('Content-Type'): 'application/octet-stream'},
            data='\xff')  # compat.str is unicode. 
Example 5
Project: SublimeBart   Author: ganemone   File: test_requests.py    MIT License 5 votes vote down vote up
def test_guess_filename_with_file_like_obj(self):
        from requests.utils import guess_filename
        from requests import compat
        fake = type('Fake', (object,), {'name': b'value'})()
        guessed_name = guess_filename(fake)
        assert b'value' == guessed_name
        assert isinstance(guessed_name, compat.bytes) 
Example 6
Project: SublimeBart   Author: ganemone   File: test_requests.py    MIT License 5 votes vote down vote up
def test_guess_filename_with_unicode_name(self):
        from requests.utils import guess_filename
        from requests import compat
        filename = b'value'.decode('utf-8')
        fake = type('Fake', (object,), {'name': filename})()
        guessed_name = guess_filename(fake)
        assert filename == guessed_name
        assert isinstance(guessed_name, compat.str) 
Example 7
Project: SublimeBart   Author: ganemone   File: test_requests.py    MIT License 5 votes vote down vote up
def test_get_auth_from_url(self):
        """Ensures that username and password in well-encoded URI as per
        RFC 3986 are correclty extracted."""
        from requests.utils import get_auth_from_url
        from requests.compat import quote
        percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "
        url_address = "request.com/url.html#test"
        url = "http://" + quote(
            percent_encoding_test_chars, '') + ':' + quote(
            percent_encoding_test_chars, '') + '@' + url_address
        (username, password) = get_auth_from_url(url)
        assert username == percent_encoding_test_chars
        assert password == percent_encoding_test_chars 
Example 8
Project: PythonGroceryList   Author: The01000001Team   File: test_requests.py    MIT License 5 votes vote down vote up
def test_unicode_header_name(self, httpbin):
        requests.put(
            httpbin('put'),
            headers={str('Content-Type'): 'application/octet-stream'},
            data='\xff')  # compat.str is unicode. 
Example 9
Project: PythonGroceryList   Author: The01000001Team   File: test_requests.py    MIT License 5 votes vote down vote up
def test_guess_filename_with_file_like_obj(self):
        from requests.utils import guess_filename
        from requests import compat
        fake = type('Fake', (object,), {'name': b'value'})()
        guessed_name = guess_filename(fake)
        assert b'value' == guessed_name
        assert isinstance(guessed_name, compat.bytes) 
Example 10
Project: PythonGroceryList   Author: The01000001Team   File: test_requests.py    MIT License 5 votes vote down vote up
def test_guess_filename_with_unicode_name(self):
        from requests.utils import guess_filename
        from requests import compat
        filename = b'value'.decode('utf-8')
        fake = type('Fake', (object,), {'name': filename})()
        guessed_name = guess_filename(fake)
        assert filename == guessed_name
        assert isinstance(guessed_name, compat.str) 
Example 11
Project: PythonGroceryList   Author: The01000001Team   File: test_requests.py    MIT License 5 votes vote down vote up
def test_get_auth_from_url(self):
        """Ensures that username and password in well-encoded URI as per
        RFC 3986 are correclty extracted."""
        from requests.utils import get_auth_from_url
        from requests.compat import quote
        percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "
        url_address = "request.com/url.html#test"
        url = "http://" + quote(
            percent_encoding_test_chars, '') + ':' + quote(
            percent_encoding_test_chars, '') + '@' + url_address
        (username, password) = get_auth_from_url(url)
        assert username == percent_encoding_test_chars
        assert password == percent_encoding_test_chars 
Example 12
Project: intake   Author: intake   File: remote.py    BSD 2-Clause "Simplified" License 4 votes vote down vote up
def open_remote(url, entry, container, user_parameters, description, http_args,
                page_size=None, auth=None, getenv=None, getshell=None):
    """Create either local direct data source or remote streamed source"""
    from intake.container import container_map
    import msgpack
    import requests
    from requests.compat import urljoin

    if url.startswith('intake://'):
        url = url[len('intake://'):]
    payload = dict(action='open',
                   name=entry,
                   parameters=user_parameters,
                   available_plugins=list(plugin_registry.keys()))
    req = requests.post(urljoin(url, '/v1/source'),
                        data=msgpack.packb(payload, **pack_kwargs),
                        **http_args)
    if req.ok:
        response = msgpack.unpackb(req.content, **unpack_kwargs)

        if 'plugin' in response:
            pl = response['plugin']
            pl = [pl] if isinstance(pl, str) else pl
            # Direct access
            for p in pl:
                if p in plugin_registry:
                    source = plugin_registry[p](**response['args'])
                    proxy = False
                    break
            else:
                proxy = True
        else:
            proxy = True
        if proxy:
            response.pop('container')
            response.update({'name': entry, 'parameters': user_parameters})
            if container == 'catalog':
                response.update({'auth': auth,
                                 'getenv': getenv,
                                 'getshell': getshell,
                                 'page_size': page_size
                                 # TODO ttl?
                                 # TODO storage_options?
                                 })
            source = container_map[container](url, http_args, **response)
        source.description = description
        return source

    else:
        raise Exception('Server error: %d, %s' % (req.status_code, req.reason)) 
Example 13
Project: open_deployment   Author: Larxel   File: open_deployment.py    MIT License 4 votes vote down vote up
def get_current_filename(jupyter_port=8888):
    '''
    # Get Current Filename
    
    # Description
        Get file name from file that executed this call
    This function is needed in order to read the file and split the code into modules

    # Arguments
        jupyter_port: int or string
            If called from within a jupyter notebook, the port where it is currently running, defaults to jupyter's default, 8888.

    # Examples
    
    # Credits
        Jupyter notebook section inspired by: https://github.com/jupyter/notebook/issues/1000
    '''
    import sys
    filetype = 'script'
    current_filename = sys.argv[0]

    # Check if it is a jupyter notebook
    if sys.argv[0].find('ipykernel_launcher') != -1:
        import json
        import os.path
        import re
        import ipykernel
        import requests
        from requests.compat      import urljoin
        from notebook.notebookapp import list_running_servers

        # Extract kernel id and retrieve list of active servers
        kernel_id = re.search('kernel-(.*).json', ipykernel.connect.get_connection_file()).group(1)
        servers   = list_running_servers()

        # Send a request to each server in order to obtain more info about it
        for server in servers:
            response = requests.get("http://127.0.0.1:" + str(jupyter_port) + "/api/sessions",
                                    params={'token': server['token']})

            # If the current notebook is the desired kernel id, return path to notebook file
            for nn in json.loads(response.text):
                if nn['kernel']['id'] == kernel_id:
                    relative_path = nn['notebook']['path']
                    return(os.path.join(server['notebook_dir'], relative_path), filetype)

    else:
        return(current_filename, filetype)