Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

python - Access dict via dict.key

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

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

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...