简体   繁体   English

Django 发送 API 请求最佳实践:内部模型保存还是序列化程序?

[英]Django send API request best practice: inside model save or serializer?

I have a model called Customer , and in the model save method, I send a request to the Stripe API to create a customer whenever a customer instance is created on my application.我有一个名为Customer的模型,在模型保存方法中,每当在我的应用程序上创建客户实例时,我都会向 Stripe API 发送请求以创建客户。 Another way I could do it is in the serializer.py file.另一种方法是在 serializer.py 文件中。 That is, when a user creates a Customer instance on my application, it will automatically send a request to stripe to create a customer on that end.也就是说,当用户在我的应用程序上创建 Customer 实例时,它会自动向 Stripe 发送请求以在该端创建客户。 Which of these is the better practice?其中哪个是更好的做法? I believe, for "updating" customers, I will have to send the request to stripe from my serializers.py file.我相信,对于“更新”客户,我将不得不从我的 serializers.py 文件中发送对条带化的请求。 So might as well do the create customer from that file too.所以也可以从该文件创建客户。 Any help would be appreciated.任何帮助,将不胜感激。

Your both approaches are correct either request Stripe in save method or after user creates a customer.无论是在 save 方法中请求 Stripe 还是在用户创建客户之后,您的两种方法都是正确的。 And you don't need serializers for updating customers.而且您不需要序列化程序来更新客户。 Simply you can do this, just an example for updating card.简单你就可以做到这一点,只是一个更新卡的例子。

def update_card(request):
    if request.method == 'POST':
    """
        replace old card with new
    """

        customer = Customer.objects.get(user=request.user).stripe_cust_id
        # Customer is my custom table that recored stripe customer information

        stripe.Customer.modify(
            customer,
            source=request.POST['stripeToken'],
        )

my template我的模板

 <form action="{% url 'subscriptions:update_card' %}" method="post" id="payment-form">{% csrf_token %}
                            <div class="card-input-wrap m-4">

                                    <label for="card-element">Credit or debit card</label>
                                    <div id="card-element">
                                        <!-- a Stripe Element will be inserted here. -->
                                    </div>

                                    <!-- Used to display form errors -->
                                    <div id="card-errors" role="alert"></div>


                            </div>
                                <button type="submit" class="btn btn-primary ml-4 mb-4">Save Info <i class="la la-save"></i></button>
   </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM