0
我正在練習python,而且我無法將我的Ruby代碼轉換爲慣用的python。Ruby中的代碼在慣用的python
我可以查詢一張卡片,但我不明白如何在一行(或儘可能簡潔)中查詢,過濾並從查詢中返回卡片。我的代碼正在變成一個try/except語句的塊,所以我猜測我錯過了一些東西。
RUBY版本
#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
https://stripe.com/docs/api/python#retrieve_card
爲什麼很重要爲此在單行?你的python代碼只是第一位,但到目前爲止似乎是合理的 – Greg
它不是,我只是認爲可能有一個更具表現力的方式,而不是一堆除了塊之外的嘗試。否則它會變成一些for循環。我會在此期間繼續嘗試 – DaynaJuliana
您能否在您的問題中添加該try-catch blob代碼的示例?我想我知道你在看什麼,但是看看你有什麼 – Greg