![](/img/trans.png)
[英]An idiomatic Python version of Ruby code with a while loop that tests a statement?
[英]Ruby code in idiomatic python
我正在練習python,但無法將Ruby代碼轉換為慣用的python。
我能夠查詢一張卡,但是我不知道如何在一行中(或盡可能簡潔地)查詢,過濾並從查詢中返回一張卡。 我的代碼正變成一堆try / except語句,因此我猜我丟失了一些東西。
紅寶石版
#fetch the customer
customer = Stripe::Customer.retrieve(self.stripe_id)
#Retrieve the card fingerprint using the stripe_card_token
card_fingerprint = Stripe::Token.retrieve(token_id).try(:card).try(:fingerprint)
# check whether a card with that fingerprint already exists
default_card = customer.sources.all(:object => "card").select{|card| card.fingerprint == card_fingerprint}.last if card_fingerprint
#create new card if do not already exists
default_card = customer.sources.create(:source => token_id) unless default_card
#set the default card of the customer to be this card, as this is the last card provided by User and probably he want this card to be used for further transactions
customer.default_card = default_card.id
# save the customer
customer.save
PYTHON版本
# fetch the customer
customer = stripe.Customer.retrieve(self.stripe_id)
# Blank default card, which will equal either an existing card or a new card
default_card
# Retrieve the card fingerprint using the stripe_card_token
card_fingerprint = stripe.Token.retrieve(token_id)
if card_fingerprint:
# Return all customer cards
default_cards = customer.sources.all(object='card')
for card in default_cards
if card.fingerprint == card_fingerprint:
# Set default card to the matching card
default_card = card
# If not card found, create a new one
if !default_card:
customer.sources.create(source=token_id)
# Set this card as default, regardless if it was new or exising
customer.default_source = default_card.id
這是我想出的最好的! 我避免了我在ruby中使用的單行if語句(Python樣式指南建議這樣做),但是對於我來說,來自Ruby的情況看起來很奇怪
PYTHON版本
# Fetch the customer
customer = stripe.Customer.retrieve(self.stripe_id)
# Retrieve the card fingerprint using the stripe_card_token
card_fingerprint = stripe.Token.retrieve(token_id)
if card_fingerprint:
cards = [x for x in customer.sources.all(object='card') if x.fingerprint == card_fingerprint]
# If a card or multiple cards return with said fingerprint, return the last one and assign default_card to this card
if cards:
default_card = cards.pop()
# If no cards matched, create a new default card
else:
default_card = customer.sources.create(source=token_id)
# Set this card as default, regardless if it was new or already existed
customer.default_source = default_card.id
customer.save()
return customer.sources.all(object='card')
我也可以將try else替換為if else,並擺脫局部變量cards
但不確定這是否是慣用的
try:
default_card = [x for x in customer.sources.all(object='card') if x.fingerprint == card_fingerprint].pop()
except IndexError e:
default_card = customer.sources.create(source=token_id)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.