Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I created a dict source = {'livemode': False}. I thought it's possible to access the livemode value via source.livemode. But it doesn't work. Is there a way to access it that way?

As a not source['livemode'] works, but I need source.livemode as that's already used in my code and I have to handle it as an alternative to the Stripe return value charge.

I want to give a bit more context

Here I create a charge via Stripe:

def _create_charge(self, request, order_reference, order_items_dict, token):
        try:
            charge = stripe.Charge.create(
                amount=order_items_dict['total_gross'],
                application_fee=order_items_dict['application_fee'],
                currency=order_items_dict['event'].currency,
                source=token,
                stripe_account=order_items_dict['event'].organizer.stripe_account,
                expand=['balance_transaction', 'application_fee'],
            )

        except stripe.error.StripeError as e:
            body = e.json_body
            err = body.get('error', {})
            messages.error(
                request,
                err.get('message')
            )

        else:
            if charge.paid and charge.status == 'succeeded':
                return charge

I can access this with e.g. charge_or_source.livemode

def _create_order(self, request, charge_or_source, order_status):
        order_reference = request.session.get('order_reference')
        new_order = self.order_form.save(commit=False)
        print(charge_or_source.livemode, "charge_or_source.livemode")
        new_order_dict = {
            'total_gross': self.order_items_dict['total_gross'],
            'livemode': charge_or_source.livemode,
        }

Now there is a case (when the order is Free) where I have to 'skip' the _create_charge function but still, I have to send information about charge_or_source.livemode. Therefore I tried to create the above-mentioned dictionary.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
298 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can implement a custom dict wrapper (either a subclass of dict or something that contains a dict) and implement __getattr__ (or __getattribute__) to return data from the dict.

class DictObject(object):
    def __init__(self, data):
        self.mydict = data
    def __getattr__(self, attr):
        if attr in self.mydict: return self.mydict[attr]
        return super(self, DictObject).__getattr__(attr)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...