bitrequests.py 文件源码

python
阅读 32 收藏 0 点赞 0 评论 0

项目:two1-python 作者: 21dotco 项目源码 文件源码
def request(self, method, url, max_price=None, mock_requests=False, **kwargs):
        """Make a 402 request for a resource.

        This is the BitRequests public method that should be used to complete a
        402 request using the desired payment method (as constructed by a class
        implementing BitRequests)

        Args:
            method (string): HTTP method for completing the request in lower-
                case letters. Examples: 'get', 'post', 'put'
            url (string): URL of the requested resource.
            data (dict): python dict of parameters to send with the request.
            max_price (int): maximum allowed price for a request (in satoshi).

        Returns:
            response (requests.response):
                response from paying for the requested resource.
        """
        if mock_requests:
            fake_response = requests.models.Response()
            fake_response.status_code = 200
            fake_response._content = b''
            return fake_response

        # Make the initial request for the resource
        response = requests.request(method, url, **kwargs)

        # Return if we receive a status code other than 402: payment required
        if response.status_code != requests.codes.payment_required:
            return response

        # Pass the response to the main method for handling payment
        logger.debug('[BitRequests] 402 payment required: {} satoshi.'.format(
            response.headers['price']))
        payment_headers = self.make_402_payment(response, max_price)

        # Reset the position of any files that have been used
        self._reset_file_positions(kwargs.get('files'), kwargs.get('data'))

        # Add any user-provided headers to the payment headers dict
        if 'headers' in kwargs:
            if isinstance(kwargs['headers'], dict):
                kwargs['headers'].update(payment_headers)
            else:
                raise ValueError('argument \'headers\' must be a dict.')
        else:
            kwargs['headers'] = payment_headers

        paid_response = requests.request(method, url, **kwargs)
        setattr(paid_response, 'amount_paid', int(response.headers['price']))

        if paid_response.status_code == requests.codes.ok:
            logger.debug('[BitRequests] Successfully purchased resource.')
        else:
            logger.debug('[BitRequests] Could not purchase resource.')

        return paid_response
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号