Python requests.utils.to_native_string() Examples

The following are 8 code examples of requests.utils.to_native_string(). 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.utils , or try the search function .
Example #1
Source File: auth.py    From coinbase-python with Apache License 2.0 6 votes vote down vote up
def __call__(self, request):
        timestamp = str(int(time.time()))
        message = timestamp + request.method + request.path_url + (request.body or '')
        secret = self.api_secret

        if not isinstance(message, bytes):
            message = message.encode()
        if not isinstance(secret, bytes):
            secret = secret.encode()

        signature = hmac.new(secret, message, hashlib.sha256).hexdigest()
        request.headers.update({
            to_native_string('CB-VERSION'): self.api_version,
            to_native_string('CB-ACCESS-KEY'): self.api_key,
            to_native_string('CB-ACCESS-SIGN'): signature,
            to_native_string('CB-ACCESS-TIMESTAMP'): timestamp,
        })
        return request 
Example #2
Source File: auth.py    From coinbase-python with Apache License 2.0 5 votes vote down vote up
def __call__(self, request):
        access_token = self.access_token_getter()
        request.headers.update({
            to_native_string('CB-VERSION'): self.api_version,
            to_native_string('Authorization'): to_native_string('Bearer {}'.format(access_token)),
        })
        return request 
Example #3
Source File: MKMOAuth1.py    From mkm-sdk with MIT License 5 votes vote down vote up
def __call__(self, r):
        r = super(MKMOAuth1, self).__call__(r)

        r.prepare_headers(r.headers)

        correct_signature = self.decode_signature(r.headers)

        r.headers.__setitem__("Authorization", correct_signature)
        r.url = to_native_string(r.url)
        return r 
Example #4
Source File: oauth1_auth.py    From Requester with MIT License 5 votes vote down vote up
def __call__(self, r):
        """Add OAuth parameters to the request.

        Parameters may be included from the body if the content-type is
        urlencoded, if no content type is set a guess is made.
        """
        # Overwriting url is safe here as request will not modify it past
        # this point.
        log.debug('Signing request %s using client %s', r, self.client)

        content_type = r.headers.get('Content-Type', '')
        if (not content_type and extract_params(r.body)
                or self.client.signature_type == SIGNATURE_TYPE_BODY):
            content_type = CONTENT_TYPE_FORM_URLENCODED
        if not isinstance(content_type, unicode):
            content_type = content_type.decode('utf-8')

        is_form_encoded = (CONTENT_TYPE_FORM_URLENCODED in content_type)

        log.debug('Including body in call to sign: %s',
                  is_form_encoded or self.force_include_body)

        if is_form_encoded:
            r.headers['Content-Type'] = CONTENT_TYPE_FORM_URLENCODED
            r.url, headers, r.body = self.client.sign(
                unicode(r.url), unicode(r.method), r.body or '', r.headers)
        elif self.force_include_body:
            # To allow custom clients to work on non form encoded bodies.
            r.url, headers, r.body = self.client.sign(
                unicode(r.url), unicode(r.method), r.body or '', r.headers)
        else:
            # Omit body data in the signing of non form-encoded requests
            r.url, headers, _ = self.client.sign(
                unicode(r.url), unicode(r.method), None, r.headers)

        r.prepare_headers(headers)
        r.url = to_native_string(r.url)
        log.debug('Updated url: %s', r.url)
        log.debug('Updated headers: %s', headers)
        log.debug('Updated body: %r', r.body)
        return r 
Example #5
Source File: __init__.py    From ttrv with MIT License 5 votes vote down vote up
def upload_image(self, subreddit, image_path, name=None,
                     header=False, upload_as=None):
        """Upload an image to the subreddit.

        :param image_path: A path to the jpg or png image you want to upload.
        :param name: The name to provide the image. When None the name will be
            filename less any extension.
        :param header: When True, upload the image as the subreddit header.
        :param upload_as: Must be `'jpg'`, `'png'` or `None`. When None, this
            will match the format of the image itself. In all cases where both
            this value and the image format is not png, reddit will also
            convert  the image mode to RGBA. reddit optimizes the image
            according to this value.
        :returns: A link to the uploaded image. Raises an exception otherwise.

        """
        if name and header:
            raise TypeError('Both name and header cannot be set.')
        if upload_as not in (None, 'png', 'jpg'):
            raise TypeError("upload_as must be 'jpg', 'png', or None.")
        with open(image_path, 'rb') as image:
            image_type = upload_as or _image_type(image)
            data = {'r': six.text_type(subreddit), 'img_type': image_type}
            if header:
                data['header'] = 1
            else:
                if not name:
                    name = os.path.splitext(os.path.basename(image.name))[0]
                data['name'] = name

            response = json.loads(self._request(
                self.config['upload_image'], data=data, files={'file': image},
                method=to_native_string('POST'), retry_on_error=False))

        if response['errors']:
            raise errors.APIException(response['errors'], None)
        return response['img_src'] 
Example #6
Source File: oauth1_auth.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, r):
        """Add OAuth parameters to the request.

        Parameters may be included from the body if the content-type is
        urlencoded, if no content type is set a guess is made.
        """
        # Overwriting url is safe here as request will not modify it past
        # this point.
        log.debug('Signing request %s using client %s', r, self.client)

        content_type = r.headers.get('Content-Type', '')
        if (not content_type and extract_params(r.body)
                or self.client.signature_type == SIGNATURE_TYPE_BODY):
            content_type = CONTENT_TYPE_FORM_URLENCODED
        if not isinstance(content_type, unicode):
            content_type = content_type.decode('utf-8')

        is_form_encoded = (CONTENT_TYPE_FORM_URLENCODED in content_type)

        log.debug('Including body in call to sign: %s',
                  is_form_encoded or self.force_include_body)

        if is_form_encoded:
            r.headers['Content-Type'] = CONTENT_TYPE_FORM_URLENCODED
            r.url, headers, r.body = self.client.sign(
                unicode(r.url), unicode(r.method), r.body or '', r.headers)
        elif self.force_include_body:
            # To allow custom clients to work on non form encoded bodies.
            r.url, headers, r.body = self.client.sign(
                unicode(r.url), unicode(r.method), r.body or '', r.headers)
        else:
            # Omit body data in the signing of non form-encoded requests
            r.url, headers, _ = self.client.sign(
                unicode(r.url), unicode(r.method), None, r.headers)

        r.prepare_headers(headers)
        r.url = to_native_string(r.url)
        log.debug('Updated url: %s', r.url)
        log.debug('Updated headers: %s', headers)
        log.debug('Updated body: %r', r.body)
        return r 
Example #7
Source File: oauth1_auth.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, r):
        """Add OAuth parameters to the request.

        Parameters may be included from the body if the content-type is
        urlencoded, if no content type is set a guess is made.
        """
        # Overwriting url is safe here as request will not modify it past
        # this point.
        log.debug('Signing request %s using client %s', r, self.client)

        content_type = r.headers.get('Content-Type', '')
        if (not content_type and extract_params(r.body)
                or self.client.signature_type == SIGNATURE_TYPE_BODY):
            content_type = CONTENT_TYPE_FORM_URLENCODED
        if not isinstance(content_type, unicode):
            content_type = content_type.decode('utf-8')

        is_form_encoded = (CONTENT_TYPE_FORM_URLENCODED in content_type)

        log.debug('Including body in call to sign: %s',
                  is_form_encoded or self.force_include_body)

        if is_form_encoded:
            r.headers['Content-Type'] = CONTENT_TYPE_FORM_URLENCODED
            r.url, headers, r.body = self.client.sign(
                unicode(r.url), unicode(r.method), r.body or '', r.headers)
        elif self.force_include_body:
            # To allow custom clients to work on non form encoded bodies.
            r.url, headers, r.body = self.client.sign(
                unicode(r.url), unicode(r.method), r.body or '', r.headers)
        else:
            # Omit body data in the signing of non form-encoded requests
            r.url, headers, _ = self.client.sign(
                unicode(r.url), unicode(r.method), None, r.headers)

        r.prepare_headers(headers)
        r.url = to_native_string(r.url)
        log.debug('Updated url: %s', r.url)
        log.debug('Updated headers: %s', headers)
        log.debug('Updated body: %r', r.body)
        return r 
Example #8
Source File: __init__.py    From rtv with MIT License 5 votes vote down vote up
def upload_image(self, subreddit, image_path, name=None,
                     header=False, upload_as=None):
        """Upload an image to the subreddit.

        :param image_path: A path to the jpg or png image you want to upload.
        :param name: The name to provide the image. When None the name will be
            filename less any extension.
        :param header: When True, upload the image as the subreddit header.
        :param upload_as: Must be `'jpg'`, `'png'` or `None`. When None, this
            will match the format of the image itself. In all cases where both
            this value and the image format is not png, reddit will also
            convert  the image mode to RGBA. reddit optimizes the image
            according to this value.
        :returns: A link to the uploaded image. Raises an exception otherwise.

        """
        if name and header:
            raise TypeError('Both name and header cannot be set.')
        if upload_as not in (None, 'png', 'jpg'):
            raise TypeError("upload_as must be 'jpg', 'png', or None.")
        with open(image_path, 'rb') as image:
            image_type = upload_as or _image_type(image)
            data = {'r': six.text_type(subreddit), 'img_type': image_type}
            if header:
                data['header'] = 1
            else:
                if not name:
                    name = os.path.splitext(os.path.basename(image.name))[0]
                data['name'] = name

            response = json.loads(self._request(
                self.config['upload_image'], data=data, files={'file': image},
                method=to_native_string('POST'), retry_on_error=False))

        if response['errors']:
            raise errors.APIException(response['errors'], None)
        return response['img_src']