【问题标题】:Ensure Saving of multiple Objects in Django service确保在 Django 服务中保存多个对象
【发布时间】:2017-04-22 07:40:24
【问题描述】:

所以,如果代码有一些缩进问题,那是由于我将它粘贴到堆栈溢出中的方式,但基本上我列出了下面列出的这个服务,它在 Django 网络服务被命中时运行。 95% 的情况下一切正常,但是如果您查看调用 .save() 的数量,有时即使运行 account.save() 也不会保存支付对象。我不熟悉调用 django commit,但由于过去的项目,我知道最好不要在一个 web 服务中列出太多 .save()。任何人都知道我可以做些什么来确保所有对象都被保存或根本没有?如果信用卡支付通过,账户对象被更新,然后支付对象永远不会被创建,即使信用卡被收费并且账户显示新的支付,这将是一个巨大的问题。

import gateway
import datetime
import smtplib
merchant = {'merchantKey': '',
            'processorId': '',
            }
data = dict(merchant)
cardNumber = request.GET.get("cardNumber", "")
cardExpYear = request.GET.get("cardExpYear", "")
cardExpMonth = request.GET.get("cardExpMonth", "")
fullName = request.GET.get("fullName", "")
accountIDOriginal = request.GET.get("accountID", "")
accountID = accountIDOriginal.split('-')[0]
if Payments.objects.filter(accountID=accountID,paymentDate=str(datetime.date.today())).count() > 0:
    return HttpResponse('You Have already ran a payment today.')
else:
    theAccount = Account.objects.get(acctno=accountID)
    collectorID = theAccount.collector_id
    collectorEmail = Collector.objects.get(pk=collectorID).email
    ownerZip = request.GET.get("ownerZip", "")
    ownerState = request.GET.get("ownerState", "")
    ownerStreet = request.GET.get("ownerStreet", "")
    ownerCity = request.GET.get("ownerCity", "")
    cVV = request.GET.get("cVV", "")
    transactionAmountString = request.GET.get("transactionAmount", "")
    transactionAmount = Decimal(transactionAmountString)
    if ownerState == "CO" or ownerState == "co" or ownerState == "Co":
        creditCardCharge = round(transactionAmount * Decimal(1.00),2)
    else:
        creditCardCharge = round(transactionAmount * Decimal(1.03),2)
    data['cardNumber'] = cardNumber
    data['cardExpMonth'] = cardExpMonth
    data['cardExpYear'] = cardExpYear
    data['ownerState'] = ownerState
    data['ownerCity'] = ownerCity
    data['ownerName'] = fullName
    data['ownerStreet'] = ownerStreet
    data['ownerState'] = ownerState
    data['ownerZip'] = ownerZip
    data['cVV'] = cVV
    data['transactionAmount'] = creditCardCharge
    sale = gateway.RestGateway(data)
    resultsCC = str(sale.createSale())
    if sale.status == 'Success':
        fromaddr = 'email@domain.com'
        subject = 'New CC Payment'
        actualaccountid = Account.objects.get(acctno=accountID).accountid
        email = str(fullName) + str(' has made a payment for the amount of ') + str(transactionAmount) + str(
        '. Account ID is ') + str(accountID) +  str("""
       https://web.domain.com/admin/web/account/""") + str(actualaccountid)
        message = 'Subject: %s\n\n%s' % (subject, email)
        username = 'emailaddress'
        password = 'password'
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.login(username, password)
        server.sendmail(fromaddr, collectorEmail, message)
        server.quit()
        previousBalance = theAccount.balance
        clientNumber = Account.objects.get(acctno=accountID).cl_no
        client = Client.objects.get(cl_no=clientNumber)
        clRates = Decimal(client.cl_rates)
        clientsRateCorrected = clRates / Decimal(100.00)
        agFee = Decimal(clientsRateCorrected) * transactionAmount
        # calculate taxes
        if client.cl_taxable == "Y":
            tax = transactionAmount * Decimal(client.cl_taxrate)
            tax = transactionAmount * Decimal(client.cl_taxrate)
        else:
            tax = '0.0'
        # calculate new balance
        newBalance = Decimal(theAccount.balance) - transactionAmount
        # save Account with new Balance
        theAccount.balance = Decimal(newBalance)
        # set new DLP
        theAccount.lastamt = transactionAmount
        theAccount.doctor_id = 3
        theAccount.lastpay = str(datetime.date.today())
        theAccount.save()
        newPayment = Payments(paymentDate=str(datetime.date.today()),
                          # claimDate='',
                          accountID_id=theAccount.acctno,
                          firstName=theAccount.first,
                          lastName=theAccount.last,
                          clientID=clientNumber,
                          pAgency=transactionAmount,
                          pClient=0.00,
                          rate=client.cl_rates,
                          agFee=agFee,
                          taxable=client.cl_taxable,
                          tax=tax,
                          # desc='',
                          fee=0.00,
                          # expense='',
                          # adjust='',
                          # salesman='',
                          balance=newBalance,
                          # intDue='',
                          status='$',
                          # area='',
                          ref_no='',
                          collector=theAccount.collector,
                          # cref_date='',
                          clName=client.cl_name,
                          # referred='',
                          # contact='',
                          isCC=True,
                          isProccessed=False,
                          creditCardChargedDate=str(datetime.date.today()),
                          )
        newPayment.save()
        paymentID = newPayment.paymentID
        handlingFee = Decimal(creditCardCharge) - Decimal(transactionAmount)
        clientName = Client.objects.get(cl_no=theAccount.cl_no).cl_name
        colelctorEmail = Collector.objects.get(name=theAccount.collector).email
        newReceipt = Invoice(paymentID=paymentID,
                         clientName=clientName,
                         accountNumber=theAccount.acctno,
                         claimNumber=theAccount.ref_no,
                         handlingFee=Decimal(handlingFee),
                         paymentAmount=Decimal(transactionAmount),
                         paymentAmountWithHandling=Decimal(creditCardCharge),
                         ccCharge=True,
                         newBalance=Decimal(newBalance),
                         previousBalance=Decimal(previousBalance),
                         originalBalance=Decimal(theAccount.referred),
                         paymentDate=str(datetime.date.today()),
                         collector=theAccount.collector,
                         fullName=fullName,
                         lastFourofCard=1234,
                         collectorEmailAddress = colelctorEmail
                         )
        newReceipt.save()
        return HttpResponse(str('https://domain.com/invoices/') + str(newReceipt.pk) + str('/') + str(theAccount.acctno) + str('/'))
   #return HttpResponse(final)
    else:
        fromaddr = 'email'
        subject = 'Error CC Payment'
        actualaccountid = Account.objects.get(acctno=accountID).accountid
        email = str(fullName) + str(' has attempted to make a payment for the amount of ') + str(transactionAmount) + str(
        '. Account ID is ') + str(accountID) + str("""

        Attached are the error results from the card being ran:
        """) +  str(resultsCC)
        message = 'Subject: %s\n\n%s' % (subject, email)
        username = 'email'
        password = 'Password'
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.login(username, password)
        server.sendmail(fromaddr, collectorEmail, message)
        server.quit()
        response = "An Error Has Occured. Please Contact ____ for Help."
        return HttpResponse(response)

【问题讨论】:

  • "如果代码有一些缩进问题,那是由于我将它粘贴到堆栈溢出中的方式" => 我们实际上不在乎 - 如果您的代码缩进严重,我们无法分辨它是什么确实在做,所以有责任修复它。

标签: django database django-models django-views django-admin


【解决方案1】:

有谁知道我可以做些什么来确保所有对象都被保存或根本不保存?

是的,它被称为事务,它是fully documented here

【讨论】:

  • 即使没有交易,有没有办法确保所有的数据都按照您认为的预期行为正确保存?
猜你喜欢
  • 2021-01-10
  • 1970-01-01
  • 2012-01-10
  • 1970-01-01
  • 2022-01-17
  • 2012-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多