<commit_before>"""Override all the things."""

import warnings

from twisted.internet import defer
import treq
import stripe
from stripe.resource import (
    Reversal as StripeReversal,
    ApplicationFeeRefund as StripeApplicationFeeRefund,
    populate_headers
)

import txstripe

from txstripe import util, api_key, error


def convert_to_stripe_object(resp, api_key, account):
    types = {'account': Account, 'charge': Charge, 'customer': Customer,
             'invoice': Invoice, 'invoiceitem': InvoiceItem,
             'plan': Plan, 'coupon': Coupon, 'token': Token, 'event': Event,
             'transfer': Transfer, 'list': ListObject, 'recipient': Recipient,
             'bank_account': BankAccount,
             'card': Card, 'application_fee': ApplicationFee,
             'subscription': Subscription, 'refund': Refund,
             'file_upload': FileUpload,
             'fee_refund': ApplicationFeeRefund,
             'bitcoin_receiver': BitcoinReceiver,
             'bitcoin_transaction': BitcoinTransaction,
             'transfer_reversal': Reversal}

    if isinstance(resp, list):
        return [convert_to_stripe_object(i, api_key, account) for i in resp]
    elif isinstance(resp, dict) and not isinstance(resp, StripeObject):
        resp = resp.copy()
        klass_name = resp.get('object')
        if isinstance(klass_name, basestring):
            klass = types.get(klass_name, StripeObject)
        else:
            klass = StripeObject
        return klass.construct_from(resp, api_key, stripe_account=account)
    else:
        return resp


stripe.resource.convert_to_stripe_object = convert_to_stripe_object


@defer.inlineCallbacks
def make_request(
    ins, method, url, stripe_account=None, params=None, headers=None, **kwargs
):
    """
    Return a deferred or handle error.

    For overriding in various classes.
    """
    if txstripe.api_key is None:
        raise error.AuthenticationError(
            'No API key provided. (HINT: set your API key using '
            '"stripe.api_key = <API-KEY>"). You can generate API keys '
            'from the Stripe web interface.  See https://stripe.com/api '
            'for details, or email <EMAIL> if you have any '
            'questions.')

    abs_url = '{}{}'.format(txstripe.api_base, url)

    ua = {
        'lang': 'python',
        'publisher': 'lextoumbourou',
        'httplib': 'Twisted',
    }

    headers = headers or {}
    headers.update({
        'X-Stripe-Client-User-Agent': util.json.dumps(ua),
        'User-Agent': 'txstripe',
        'Authorization': 'Bearer %s' % (txstripe.api_key,)
    })

    if stripe_account:
        headers['Stripe-Account'] = stripe_account

    if txstripe.api_version is not None:
        headers['Stripe-Version'] = txstripe.api_version

    if method == 'get' or method == 'delete':
        data = None
    elif method == 'post':
        data = params
        params = None
    else:
        raise error.APIConnectionError(
            'Unrecognized HTTP method %r.  This may indicate a bug in the '
            'Stripe bindings.' % (method,))

    resp = yield treq.request(
        method, abs_url, params=params, data=data, headers=headers, **kwargs)

    if resp.code >= 400:
        yield util.handle_api_error(resp)
        return

    body = yield resp.json()

    defer.returnValue(
        convert_to_stripe_object(
            body, txstripe.api_key, stripe_account))


class StripeObject(stripe.StripeObject):

    """Override blocking method."""

    def request(self, method, url, params=None, headers=None):
        """Return a deferred."""<commit_msg>Use _api_encode function in post requests.<commit_after>"""Override all the things."""

import warnings

from twisted.internet import defer
import treq
import stripe
from stripe.resource import (
    Reversal as StripeReversal,
    ApplicationFeeRefund as StripeApplicationFeeRefund,
    populate_headers
)
from stripe.api_requestor import _api_encode

import txstripe

from txstripe import util, api_key, error


def convert_to_stripe_object(resp, api_key, account):
    types = {'account': Account, 'charge': Charge, 'customer': Customer,
             'invoice': Invoice, 'invoiceitem': InvoiceItem,
             'plan': Plan, 'coupon': Coupon, 'token': Token, 'event': Event,
             'transfer': Transfer, 'list': ListObject, 'recipient': Recipient,
             'bank_account': BankAccount,
             'card': Card, 'application_fee': ApplicationFee,
             'subscription': Subscription, 'refund': Refund,
             'file_upload': FileUpload,
             'fee_refund': ApplicationFeeRefund,
             'bitcoin_receiver': BitcoinReceiver,
             'bitcoin_transaction': BitcoinTransaction,
             'transfer_reversal': Reversal}

    if isinstance(resp, list):
        return [convert_to_stripe_object(i, api_key, account) for i in resp]
    elif isinstance(resp, dict) and not isinstance(resp, StripeObject):
        resp = resp.copy()
        klass_name = resp.get('object')
        if isinstance(klass_name, basestring):
            klass = types.get(klass_name, StripeObject)
        else:
            klass = StripeObject
        return klass.construct_from(resp, api_key, stripe_account=account)
    else:
        return resp


stripe.resource.convert_to_stripe_object = convert_to_stripe_object


@defer.inlineCallbacks
def make_request(
    ins, method, url, stripe_account=None, params=None, headers=None, **kwargs
):
    """
    Return a deferred or handle error.

    For overriding in various classes.
    """
    if txstripe.api_key is None:
        raise error.AuthenticationError(
            'No API key provided. (HINT: set your API key using '
            '"stripe.api_key = <API-KEY>"). You can generate API keys '
            'from the Stripe web interface.  See https://stripe.com/api '
            'for details, or email <EMAIL> if you have any '
            'questions.')

    abs_url = '{}{}'.format(txstripe.api_base, url)

    ua = {
        'lang': 'python',
        'publisher': 'lextoumbourou',
        'httplib': 'Twisted',
    }

    headers = headers or {}
    headers.update({
        'X-Stripe-Client-User-Agent': util.json.dumps(ua),
        'User-Agent': 'txstripe',
        'Authorization': 'Bearer %s' % (txstripe.api_key,)
    })

    if stripe_account:
        headers['Stripe-Account'] = stripe_account

    if txstripe.api_version is not None:
        headers['Stripe-Version'] = txstripe.api_version

    if method == 'get' or method == 'delete':
        data = None
    elif method == 'post':
        data = {k: v for (k, v) in _api_encode(params)}
        params = None
    else:
        raise error.APIConnectionError(
            'Unrecognized HTTP method %r.  This may indicate a bug in the '
            'Stripe bindings.' % (method,))

    resp = yield treq.request(
        method, abs_url, params=params, data=data, headers=headers, **kwargs)

    if resp.code >= 400:
        yield util.handle_api_error(resp)
        return

    body = yield resp.json()

    defer.returnValue(
        convert_to_stripe_object(
            body, txstripe.api_key, stripe_account))


class StripeObject(stripe.StripeObject):

    """Override blocking method."""

    def request(self, method, url, params=None, headers=None):
        """Return a deferred."""
{'fraction_non_alphanumeric': 0.11050626020685901, 'fraction_numerical': 0.0008165487207403375, 'mean_word_length': 2.7078708375378406, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1418276', 'n_tokens_mistral': 2248, 'n_tokens_neox': 2160, 'n_words': 582}