当前位置: 首页>>代码示例>>Python>>正文


Python Transaction.save方法代码示例

本文整理汇总了Python中models.Transaction.save方法的典型用法代码示例。如果您正苦于以下问题:Python Transaction.save方法的具体用法?Python Transaction.save怎么用?Python Transaction.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在models.Transaction的用法示例。


在下文中一共展示了Transaction.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_model_transaction

# 需要导入模块: from models import Transaction [as 别名]
# 或者: from models.Transaction import save [as 别名]
    def test_model_transaction(self):
        "Test transaction model"
        contact_type = ContactType(name='test')
        contact_type.save()

        contact = Contact(name='test', contact_type=contact_type)
        contact.save()

        currency = Currency(code="GBP",
                            name="Pounds",
                            symbol="L",
                            is_default=True)
        currency.save()

        account = Account(
            name='test', owner=contact, balance_currency=currency)
        account.save()

        obj = Transaction(name='test',
                          account=account,
                          source=contact,
                          target=contact,
                          value=10,
                          value_currency=currency)
        obj.save()
        self.assertEquals('test', obj.name)
        self.assertNotEquals(obj.id, None)
        obj.delete()
开发者ID:tovmeod,项目名称:anaf,代码行数:30,代码来源:tests.py

示例2: add

# 需要导入模块: from models import Transaction [as 别名]
# 或者: from models.Transaction import save [as 别名]
def add(request, portfolio, is_sample, read_only):
  form = TransactionForm(request.POST)
  if form.is_valid():
    commission = form.cleaned_data.get('commission')
    if commission == None:
      commission = 0.0
    
    type = form.cleaned_data.get('type').encode('UTF-8')
    
    symbol = form.cleaned_data.get('symbol').encode('UTF-8').upper()
    linked_symbol = None
    if type == 'ADJUST':
      linked_symbol = symbol
      
    if type in ['DEPOSIT', 'WITHDRAW', 'ADJUST']:
      symbol = CASH_SYMBOL
    
    if symbol != None and len(symbol) > 0:
      transaction = Transaction()
      transaction.portfolio = portfolio
      transaction.type = type
      transaction.as_of_date = form.cleaned_data.get('as_of_date')
      transaction.symbol = symbol
      transaction.quantity = form.cleaned_data.get('quantity')
      transaction.price = form.cleaned_data.get('price')
      transaction.total = (transaction.quantity * transaction.price) + commission
      transaction.linked_symbol = linked_symbol
      transaction.save()
    
      refresh_positions(portfolio, force = True)
  
  return redirect_to_portfolio_action('transactions', portfolio)
开发者ID:andlister,项目名称:frano,代码行数:34,代码来源:views.py

示例3: process_import

# 需要导入模块: from models import Transaction [as 别名]
# 或者: from models.Transaction import save [as 别名]
def process_import(request, portfolio, is_sample, read_only):
  formset = ImportTransactionFormSet(request.POST)
  if not formset.is_valid():
    raise Exception('Invalid import set');
  
  for form in formset.forms:
    cd = form.cleaned_data
    
    if not cd.get('exclude'):
      transaction = Transaction()
      transaction.portfolio = portfolio
      transaction.type = cd.get('type').encode('UTF-8')
      transaction.as_of_date = cd.get('as_of_date')
      transaction.symbol = cd.get('symbol').encode('UTF-8').upper()
      transaction.quantity = cd.get('quantity')
      transaction.price = cd.get('price')
      transaction.total = cd.get('total')
      
      linked_symbol = cd.get('linked_symbol').encode('UTF-8')
      if linked_symbol != None and linked_symbol != '':
        transaction.linked_symbol = linked_symbol
        
      transaction.save()
    
  refresh_positions(portfolio, force = True)
  return redirect_to_portfolio_action('transactions', portfolio)
开发者ID:andlister,项目名称:frano,代码行数:28,代码来源:views.py

示例4: transaction

# 需要导入模块: from models import Transaction [as 别名]
# 或者: from models.Transaction import save [as 别名]
def transaction(request, start=False):
    """
        Start a transaction with Fermi
        @param request: request object
        @param start: if True, a new transaction will be started if we didn't already have one
    """
    if start is not True:
        transID = request.session.get('fermi_transID', None)
        if transID is not None:
            transactions = Transaction.objects.filter(trans_id=transID)
            if len(transactions)>0:
                return transactions[0]
    try:
        conn = httplib.HTTPSConnection(settings.FERMI_HOST, timeout=0.5)
        conn.request('GET', settings.FERMI_BASE_URL+'transaction?Action=Start',
                            headers={'Cookie':request.session.get('fermi', '')})
        r = conn.getresponse()
        if not r.status == 200:
            logging.error("Fermi transaction call failed: %s" % r.status)
        info = json.loads(r.read())
        if "Err_Msg" in info:
            logging.error("MantidRemote: %s" % info["Err_Msg"])

        request.session['fermi_transID'] = info["TransID"]
        transaction_obj = Transaction(trans_id = info["TransID"],
                                  directory = info["Directory"],
                                  owner = request.user)
        transaction_obj.save()
        return transaction_obj
    except:
        logging.error("Could not get new transaction ID: %s" % sys.exc_value)
    return None
开发者ID:serena617,项目名称:reduction_service,代码行数:34,代码来源:view_util.py

示例5: get_post_function

# 需要导入模块: from models import Transaction [as 别名]
# 或者: from models.Transaction import save [as 别名]
def get_post_function(request,t_id,rf_id,amt=0.0,l_or_s_or_c=None,date_time=None):
	loan_balance = 0.0
	savings_balance = 0.0
	try:
		customer = Customer.objects.get(RfCard_id=rf_id)
		if int(l_or_s_or_c) == 0: #i.e loan

			loan_amt = float(customer.loanAmount) - float(amt)
			trans_type = 'Loan'
			customer.loanAmount = loan_amt
			customer.save()
			
		elif int(l_or_s_or_c) == 1: #i.e savings
			savings_balance = float(customer.savingsAmount) + float(amt)
			trans_type = 'Savings'
			customer.savingsAmount = savings_balance
			customer.save()
		
		elif int(l_or_s_or_c) == 2: #i.e collections
			collection_amt = float(customer.collectionAmount) - float(amt)
			trans_type = 'Collections'
			customer.collectionAmount = collection_amt
			customer.save()

		else:
			return HttpResponseForbidden("You do not have permission!!")
          
               
   		#random codes from online
		#random_number = User.objects.make_random_password(length=20, allowed_chars='123456789')

		#while User.objects.filter(userprofile__temp_password=random_number):
    		#	random_number = User.objects.make_random_password(length=10, allowed_chars='123456789')
		
			
		
               # key = hashlib.new(str(random.random()))
		trans_id_gen = random.randint(1,1000000000000)
            	#trans_id_gen = hashlib.new('TRANS'+str(key)).hexdigest()

               

		trans = Transaction(transaction_type=trans_type,paymentAmount = float(amt),terminal_id = t_id,transaction_id = trans_id_gen,RfCard_id =  rf_id,status=l_or_s_or_c, company=customer.company, customer_name=customer.name, collector_id = str(request.user.username))
		trans.save()
		#return HttpResponse('Name: '+str(customer.name)+'<br/>'+ 'Amount Paid: GHS '+str(trans.paymentAmount)+'<br/>'+ 'Loan Balance: GHS '+ str(customer.loanAmount)+'<br/>'+'Transaction Type: '+ trans_type+'<br/>'+'Transaction Id: '+str(trans_id_gen)+'<br/>')
		#print 'blupay1'
                pwdBy = PoweredBy.objects.get(pk=1)
		if trans_type == 'Loan':
			return HttpResponse('<b>'+str(customer.company)+'</b></br></br>LOAN REPAYMENT RECEIPT<br/>***************************</br>'+'Name: '+str(customer.name)+'<br/>'+ 'Amount Paid: GHS '+str(trans.paymentAmount)+'<br/>'+ 'Loan Balance: GHS '+ str(customer.loanAmount)+'<br/>'+'Transaction Id: '+str(trans_id_gen)+'<br/>'+'Timestamp: '+str(trans.date_created)+'<br/>***************************</br>Powered by <b>'+pwdBy.poweredByName+'&#0174;</b>')
			#return HttpResponseRedirect('https://dev.jallohenterprise.co.uk/visiontekconnect.php?userid=visiontek&password=12345&amount='+str(customer.loanAmount))
		elif trans_type == 'Savings':
			return HttpResponse('<b>'+str(customer.company)+'</b></br></br>SAVINGS RECEIPT<br/>***************************</br>'+'Name: '+str(customer.name)+'<br/>'+ 'Amount Paid: GHS '+str(trans.paymentAmount)+'<br/>'+ 'Savings Balance: GHS '+ str(customer.savingsAmount)+'<br/>'+'Transaction Id: '+str(trans_id_gen)+'<br/>'+'Timestamp: '+str(trans.date_created)+'<br/>***************************</br>Powered by <b>'+pwdBy.poweredByName+'&#0174;</b>')
			#return HttpResponseRedirect('https://dev.jallohenterprise.co.uk/visiontekconnect.php?userid=visiontek&password=12345&amount='+str(customer.savingsAmount))
		else:
			return HttpResponse('<b>'+str(customer.company)+'</b></br></br>COLLECTION REPAYMENT RECEIPT<br/>***************************</br>'+'Name: '+str(customer.name)+'<br/>'+ 'Amount Paid: GHS '+str(trans.paymentAmount)+'<br/>'+ 'Collection Balance: GHS '+ str(customer.collectionAmount)+'<br/>'+'Transaction Id: '+str(trans_id_gen)+'<br/>'+'Timestamp: '+str(trans.date_created)+'<br/>***************************</br>Powered by <b>'+pwdBy.poweredByName+'&#0174;</b>')

	except Customer.DoesNotExist:	
		return HttpResponseForbidden("Forbidden!!, Customer does not exist!!")
开发者ID:blupay,项目名称:BLUPAY,代码行数:60,代码来源:views.py

示例6: init

# 需要导入模块: from models import Transaction [as 别名]
# 或者: from models.Transaction import save [as 别名]
def init(amount, currency=None, email="", description="", language=None):
    """
    Init payment

    Params:
    * amount - Amount to pay
    * currency - Suggested currency (can be changed by user)
    * email - User's email (can be changed by user)
    * description - Transaction description
    * language - "en" or "ru"

    Return tuple (rk.models.Transaction instance, robokassa redirect URL)
    """

    from models import Transaction

    if amount is None:
        return None

    currency = currency or lib.conf("RK_DEFAULT_CURRENCY")
    language = language or lib.conf("RK_DEFAULT_LANGUAGE")

    login = lib.conf("RK_MERCHANT_LOGIN")
    pass1 = lib.conf("RK_MERCHANT_PASS1")

    # 2. Create transaction in DB
    tr = Transaction(amount=amount, currency=currency, description=description)
    tr.save()
    _id = tr.id

    signature = lib.sign([login, amount, str(_id), pass1])

    # 3. Redirect to robokassa
    params = {"MrchLogin": login,
              "OutSum": amount,
              "InvId": _id,
              "Desc": description,
              "SignatureValue": signature,
              "IncCurrLabel": currency,
              "Email": email,
              "Culture": language}

    if lib.conf("RK_USE_TEST_SERVER"):
        rk_url = lib.conf("RK_TEST_URL")
    else:
        rk_url = lib.conf("RK_URL")

    url = rk_url + "?%s" % urllib.urlencode(params)

    return (tr, url)
开发者ID:muzmates,项目名称:django-rk,代码行数:52,代码来源:__init__.py

示例7: route_webhook

# 需要导入模块: from models import Transaction [as 别名]
# 或者: from models.Transaction import save [as 别名]
def route_webhook():
    data = json.loads(request.data.decode('utf8'))

    if data['type'] == 'transaction.created':
        transaction = Transaction(data['data'])
        transaction.save()

        if transaction.visited_count > settings.mondo_visit_count:
            suggestion = transaction.find_suggestion()

            if suggestion:
                suggestion.save()
                suggestion.post_to_feed()

    else:
        log.warning('Unsupported webhook type: %s' % data['type'])

    return ''
开发者ID:markdessain,项目名称:goto-mondo,代码行数:20,代码来源:main.py

示例8: run_billing

# 需要导入模块: from models import Transaction [as 别名]
# 或者: from models.Transaction import save [as 别名]
def run_billing(bill_time=datetime.now()):
	"""Generate billing records for every member who deserves it."""
	bill_date = datetime.date(bill_time)
	print "Running billing for %s" % bill_date
	try:
		latest_billing_log = BillingLog.objects.latest()
	except ObjectDoesNotExist:
		latest_billing_log = None
	if latest_billing_log and not latest_billing_log.ended:
		print 'The last billing log (%s) claims to be in progress.	Aborting billing.' % latest_billing_log
		return

	billing_log = BillingLog.objects.create()
	billing_success = False
	bill_count = 0
	try:
			for member in Member.objects.all():
				last_bill = member.last_bill()
				if last_bill:
					start_date = last_bill.created + timedelta(days=1)
				else:
					start_date = bill_date - timedelta(days=62)
					if start_date < settings.BILLING_START_DATE: start_date = settings.BILLING_START_DATE
				run = Run(member, start_date, bill_date)
				for day_index in range(0, len(run.days)): # look for days on which we should bill for a membership
					day = run.days[day_index]
					if day.is_membership_anniversary() or day.is_membership_end_date(): # calculate a member bill
						bill_dropins = []
						bill_guest_dropins = []
						recent_days = run.days[0:day_index + 1]
						recent_days.reverse()
						for recent_day in recent_days: # gather the daily logs for this member and guests under this membership
							if recent_day.bill:
								break
							if recent_day.daily_log: bill_dropins.append(recent_day.daily_log)
							for guest_daily_log in recent_day.guest_daily_logs: bill_guest_dropins.append(guest_daily_log)
						# now calculate the bill amount
						bill_amount = 0
						monthly_fee = day.membership.monthly_rate
						if day.is_membership_end_date(): monthly_fee = 0
						billable_dropin_count = max(0, len(bill_dropins) + len(bill_guest_dropins) - day.membership.dropin_allowance)
						bill_amount = monthly_fee + (billable_dropin_count * day.membership.daily_rate)

						day.bill = Bill(created=day.date, amount=bill_amount, member=member, paid_by=day.membership.guest_of, membership=day.membership)
						#print 'saving bill: %s - %s - %s' % (day.bill, day, billable_dropin_count)
						day.bill.save()
						bill_count += 1
						day.bill.dropins = [dropin.id for dropin in bill_dropins]
						day.bill.guest_dropins = [dropin.id for dropin in bill_guest_dropins]
						day.bill.save()

						# Close out the transaction if no money is due
						if bill_amount == 0:
							transaction = Transaction(member=member, amount=0, status='closed')
							transaction.save()
							transaction.bills = [day.bill]
							transaction.save()

				# Now calculate a bill for non-member drop-ins if they exist and it has been two weeks since we billed them
				bill_dropins, guest_bill_dropins = run.non_member_daily_logs()
				if len(bill_dropins) > 0 or len(guest_bill_dropins) > 0:
					time_to_bill_guests = len(guest_bill_dropins) > 0 and (bill_date - guest_bill_dropins[0].visit_date) >= timedelta(weeks=2)
					time_to_bill_dropins = len(bill_dropins) > 0 and (bill_date - bill_dropins[0].visit_date) >= timedelta(weeks=2)
					if time_to_bill_guests or time_to_bill_dropins:
						bill_amount = (len(bill_dropins) + len(guest_bill_dropins)) * settings.NON_MEMBER_DROPIN_FEE
						last_day = run.days[len(run.days) - 1]
						last_day.bill = Bill(created=last_day.date, amount=bill_amount, member=member)
						last_day.bill.save()
						bill_count += 1
						last_day.bill.dropins = [dropin.id for dropin in bill_dropins]
						last_day.bill.guest_dropins = [dropin.id for dropin in guest_bill_dropins]
						last_day.bill.save()

			billing_success = True
			#print 'Successfully created %s bills' % bill_count
	except:
		billing_log.note = traceback.format_exc()
	finally:
		billing_log.ended = datetime.now()
		billing_log.successful = billing_success
		billing_log.save()
		#print 'Completed billing %s' % billing_success
		if not billing_success: print billing_log.note
开发者ID:ponyfleisch,项目名称:nadine,代码行数:85,代码来源:billing.py

示例9: create_transaction

# 需要导入模块: from models import Transaction [as 别名]
# 或者: from models.Transaction import save [as 别名]
def create_transaction(request):
    if request.method == 'POST':
        form = TransactionForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data

            invalid_response ={"message": "No transaction was created. The transaction failed due to the following error(s).",
                               "code": 500,
                               "errors": []}
            if data.has_key('points'):

                if data['points']:
                    try:
                        p=Permission.objects.get(user=request.user,
                                                permission_name='assign-points')

                    except(Permission.DoesNotExist):
                        invalid_response['errors'].append("You do not have permission to assign points.")
                        invalid_response['code'] = 401
                        jsonstr=json.dumps(invalid_response, indent = 4,)
                        return HttpResponse(jsonstr, mimetype="application/json")



            if settings.USERS_MUST_EXIST:
                data = verify_users_exist_and_sg(data)

                if data.has_key('errors'):
                    invalid_response['errors'].append(data['errors'])
                    jsonstr=json.dumps(invalid_response, indent = 4,)
                    return HttpResponse(jsonstr, mimetype="application/json")

            tx=Transaction(**data)
            result=tx.save()

            if int(result['code']) != 200:
                #print "result =", result
                jsonstr={"code": int(result['code']),
                         "message": result['message'],
                         "errors": result['errors']}
            else:
                jsonstr={"code": 200,
                         "message": "Transaction created.",
                         "results": (result['results'],)}

                jsonstr=json.dumps(jsonstr, indent = 4,)
                return HttpResponse(jsonstr, mimetype="application/json")
        else:
            # the form had errors
            errors=[]
        if form.non_field_errors():
            global_error={'global':global_error}
            errors.append()


        for k,v in form._errors.items():
            error={'field': k, 'description':v}
            errors.append(error)
            jsonstr={"code": 500,
                     "message": "No transaction was created. The transaction failed due to the following error(s). ",
                     "errors": errors}
            jsonstr=json.dumps(jsonstr, indent = 4,)
            return HttpResponse(jsonstr, status=500, mimetype="application/json")

    #this is an HTTP GET
    return render_to_response('transaction/create.html',
        {'form': TransactionForm(),}, RequestContext(request))
开发者ID:ekivemark,项目名称:flangio,代码行数:69,代码来源:views.py

示例10:

# 需要导入模块: from models import Transaction [as 别名]
# 或者: from models.Transaction import save [as 别名]
				title = row[14],
				language = row[15],
				material = row[16],
				place = row[17],
				use = row[18],
				date = row[19],
				circa = row[20],
				artist = row[21],
				script = row[22],
				folios = row[23],
				lines = row[24],
				height = row[25],
				width = row[26],
				binding = row[27],
				provenance = row[28],
				comments = row[29],
				link = row[30],
				full_page_mini = row[31],
				large_mini = row[32],
				small_mini = row[33],
				mini = row[34],
				historiated_initials = row[35],
				decorated_initials = row[35],
				possible_duplicates = row[44],
				cat_date = row[47],
				buyer = row[48],
				columns = row[49],
				)
			print trans.manuscript_id
			trans.save()
开发者ID:samzhang111,项目名称:schoenberg-visualization,代码行数:32,代码来源:import_all.py

示例11: FinanceViewsTest

# 需要导入模块: from models import Transaction [as 别名]
# 或者: from models.Transaction import save [as 别名]
class FinanceViewsTest(TestCase):
    username = "test"
    password = "password"

    def setUp(self):
        self.group, created = Group.objects.get_or_create(name='test')
        self.user, created = DjangoUser.objects.get_or_create(username=self.username)
        self.user.set_password(self.password)
        self.user.save()
        perspective, created = Perspective.objects.get_or_create(name='default')
        perspective.set_default_user()
        perspective.save()
        ModuleSetting.set('default_perspective', perspective.id)

        self.contact_type = ContactType(name='test')
        self.contact_type.set_default_user()
        self.contact_type.save()

        self.contact = Contact(name='test', contact_type=self.contact_type)
        self.contact.set_default_user()
        self.contact.save()

        self.category = Category(name='test')
        self.category.set_default_user()
        self.category.save()

        self.equity = Equity(
            issue_price=10, sell_price=10, issuer=self.contact, owner=self.contact)
        self.equity.set_default_user()
        self.equity.save()

        self.asset = Asset(name='test', owner=self.contact)
        self.asset.set_default_user()
        self.asset.save()

        self.tax = Tax(name='test', rate=10)
        self.tax.set_default_user()
        self.tax.save()

        self.currency = Currency(code="GBP",
                                 name="Pounds",
                                 symbol="L",
                                 is_default=True)
        self.currency.set_default_user()
        self.currency.save()

        self.account = Account(
            name='test', owner=self.contact, balance_currency=self.currency)
        self.account.set_default_user()
        self.account.save()

        self.liability = Liability(name='test',
                                   source=self.contact,
                                   target=self.contact,
                                   account=self.account,
                                   value=10,
                                   value_currency=self.currency)
        self.liability.set_default_user()
        self.liability.save()

        self.transaction = Transaction(name='test', account=self.account, source=self.contact,
                                       target=self.contact, value=10, value_currency=self.currency)
        self.transaction.set_default_user()
        self.transaction.save()

    ######################################
    # Testing views when user is logged in
    ######################################
    def test_finance_login(self):
        """Test index page with login at /finance/"""
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('finance'))
        self.assertEquals(response.status_code, 200)

    def test_finance_index_login(self):
        "Test index page with login at /finance/index/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('finance_index_transactions'))
        self.assertEquals(response.status_code, 200)

    def test_finance_income(self):
        "Test index page with login at /finance/income/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('finance_income_view'))
        self.assertEquals(response.status_code, 200)

    def test_finance_balance(self):
        "Test index page with login at /finance/balance/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('finance_balance_sheet'))
        self.assertEquals(response.status_code, 200)

#.........这里部分代码省略.........
开发者ID:tovmeod,项目名称:anaf,代码行数:103,代码来源:tests.py

示例12: transfer_funds

# 需要导入模块: from models import Transaction [as 别名]
# 或者: from models.Transaction import save [as 别名]
def transfer_funds(tokens, sender_number):
    """
    Transfer funds to user or non-user
    Expected format: 'transfer [amount] [receiver] [pin]'
    
    transaction limit: NGN3,000
    daily transaction limit: NGN30,000
    """
    messages = []
    try:
        amount = float(tokens[1])
        receiver_number = tokens[2]
        pin = tokens[3]
        
        user = User.objects.get(phone=sender_number)
        if not validate_pin(user, pin):
            return msg_invalid_pin(user.phone)
        
        if not account_activated(user):
            return msg_account_not_activated(user.phone)
        
        # check account balance
        if amount > (user.balance - 100):
            msg = ("You do not have enough balance to make this transfer.")
            sms = OutgoingMessage(body=msg, receiver=sender_number,
                                  timestamp=time.time(), 
                                  type='insufficient_balance')
            messages.append(sms)
            return send_sms(messages)
        
        if amount > 3000:
            msg = ("You cannot transfer above NGN3,000 in one transaction."
                   " Please try again.")
            sms = OutgoingMessage(body=msg, receiver=sender_number,
                                  timestamp=time.time(), type='excess_transfer')
            messages.append(sms)
            return send_sms(messages)
        
        # add restriction of daily limit of 3ok
        
        # validate receiver exists
        #     if not generate cash out ticket instead
        transaction = Transaction(
            id=util.generate_uuid()[0:12], sender=user.phone, 
            receiver=receiver_number, timestamp=time.time(), amount=amount)
        try:
            User.objects.get(phone=receiver_number)
            transaction.type = 'user_to_user_transfer'
        except User.DoesNotExist:
            transaction.type = 'user_to_guest_transfer'
            
        transaction.save()
        
        # return message to confirm transaction
        msg = ("transaction-id: %s, amount: %s, receiver: %s. Please"
               " reply this message with 'confirm' to confirm this"
               " transaction." 
               % (transaction.id, transaction.amount, transaction.receiver))
        sms = OutgoingMessage(body=msg, receiver=sender_number,
                              timestamp=time.time(), meta=transaction,
                              type='confirm_transaction')
        messages.append(sms)
        return send_sms(messages)
        
    except User.DoesNotExist:
        return msg_user_does_not_exist(sender_number)
    
    except IndexError:
        expected_format = ("Unknown message format. Expeted format: transfer"
                           " [amount] [receiver] [pin]. Please try again.")
        return msg_unknown_format(expected_format, sender_number)
开发者ID:stackempty,项目名称:mopay,代码行数:73,代码来源:actions.py

示例13: make_payment

# 需要导入模块: from models import Transaction [as 别名]
# 或者: from models.Transaction import save [as 别名]
def make_payment(content_object, request, transaction_opts={}):
  """"""

  trans = Transaction(content_object=content_object)
  trans.status = Transaction.PROCESSING
  trans.save()

  total = content_object.get_amount()
  shipping = content_object.shipping_cost()
  subtotal = (total - shipping)

  post_data = {
    'intent':'sale',
    'redirect_urls':{
        'return_url': build_url(request, trans.get_success_url()),
        'cancel_url': build_url(request, trans.get_failure_url()),
    },
    'payer':{
        'payment_method': 'paypal',
    },
    'transactions': [{
      'amount': {
        'total': "%.2f" % total,
        'currency': content_object.currency,
        'details': {
          'subtotal': "%.2f" % subtotal,
          'shipping': "%.2f" % shipping,
        }
      },
      'description': str(content_object).encode('ascii', 'ignore'),
      'item_list': {'items': []},
    }]
  }

  if hasattr(content_object, 'get_lines'):
    for line in content_object.get_lines():
      post_data['transactions'][0]['item_list']['items'].append({
        'name': '%s x %s' % (line[1], line[0]),
        'quantity': 1,
        'price': "%.2f" % line[2],
        'currency': content_object.currency,
      })
  else:
    post_data['transactions'][0]['item_list']['items'].append({
      'quantity': 1,
      'name': str(content_object).encode('ascii', 'ignore'),
      'price': "%.2f" % subtotal,
      'currency': content_object.currency,
    })

  url = PAYPAL_API + '/v1/payments/payment'
  token = get_paypal_token()

  # see https://developer.paypal.com/docs/integration/web/accept-paypal-payment/#specify-payment-information-to-create-a-payment

  opener = urllib2.build_opener(BetterHTTPErrorProcessor)
  urllib2.install_opener(opener)

  encoded_data = json.dumps(post_data)

  request = urllib2.Request(url, encoded_data,
                            headers={"Authorization": 'Bearer ' + token,
                                     "Content-Type": 'application/json'})
  try:
    request = urllib2.Request(url, encoded_data,
                              headers={"Authorization": 'Bearer ' + token,
                                       "Content-Type": 'application/json'})
    result = urllib2.urlopen(request).read()
  except urllib2.HTTPError, e:
    raise Exception(e.read())
开发者ID:pbright,项目名称:django-shoptools,代码行数:72,代码来源:transactions.py

示例14: load_transactions

# 需要导入模块: from models import Transaction [as 别名]
# 或者: from models.Transaction import save [as 别名]

#.........这里部分代码省略.........
      addr_final = row[20].strip()
      city_final = row[21].strip()
      try:	lat_y = float(row[22])
      except:	lat_y = None
      try:	long_x = float(row[23])
      except:   long_x = None
      try:	tract_fix = float(row[24])
      except:	tract_fix = None
      no_tract_info = True if int(row[25])==1 else False
      try:	ca_num = int(row[26])
      except:	ca_num = None
      ca_name = row[27].strip()
      place = row[28].strip()
      gisdate = row[29].strip()
      try:	ptype_id = int(row[30])
      except:   ptype_id = None
      try: 	residential = int(row[31])
      except:	residential = None
      try:	adj_yq = int(row[32])
      except:   adj_yq = None
      try:	adj_yd = int(row[33])
      except:	adj_yd = None
      loc       = None if row[22]=='' else Point((Decimal(row[23]), Decimal(row[22])),srid=4326).transform(3435)
      try:
        if skip_lookup:
          raise Exception('no lookup')
        transaction =  Transaction.objects.get(\
        pin = pin\
	,amount_prime = amount_prime\
        ,doc = doc\
        ,date_doc = date_doc\
	,date_rec = date_rec\
	,buyer = buyer\
	,buyer_type = buyer_type\
	,seller = seller\
	,seller_type = seller_type\
	,non_condo = non_condo\
	,purchase_less_20k = purchase_less_20k\
	,business_buyer = business_buyer\
        ,yq_doc = yq_doc\
	,yeard = yeard\
	,apt = apt\
	,direction = direction\
	,houseno = houseno\
	,street = street\
	,suffix = suffix\
	,addr_final = addr_final\
	,city_final = city_final\
	,lat_y = lat_y\
	,long_x = long_x\
	,tract_fix = tract_fix\
	,no_tract_info = no_tract_info\
	,ca_num = ca_num\
	,ca_name = ca_name\
	,place = place\
	,gisdate = gisdate\
	,ptype_id = ptype_id\
	,residential = residential\
	,adj_yq = adj_yq\
	,adj_yd = adj_yd\
        ,loc = loc\
        )
      except:
        transaction =  Transaction(\
        pin = pin\
	,amount_prime = amount_prime\
        ,doc = doc\
        ,date_doc = date_doc\
	,date_rec = date_rec\
	,buyer = buyer\
	,buyer_type = buyer_type\
	,seller = seller\
	,seller_type = seller_type\
	,non_condo = non_condo\
	,purchase_less_20k = purchase_less_20k\
	,business_buyer = business_buyer\
        ,yq_doc = yq_doc\
	,yeard = yeard\
	,apt = apt\
	,direction = direction\
	,houseno = houseno\
	,street = street\
	,suffix = suffix\
	,addr_final = addr_final\
	,city_final = city_final\
	,lat_y = lat_y\
	,long_x = long_x\
	,tract_fix = tract_fix\
	,no_tract_info = no_tract_info\
	,ca_num = ca_num\
	,ca_name = ca_name\
	,place = place\
	,gisdate = gisdate\
	,ptype_id = ptype_id\
	,residential = residential\
	,adj_yq = adj_yq\
	,adj_yd = adj_yd\
        ,loc = loc\
        )
      transaction.save()
开发者ID:Najah-lshanableh,项目名称:land-bank,代码行数:104,代码来源:load_tran.py

示例15: transaction

# 需要导入模块: from models import Transaction [as 别名]
# 或者: from models.Transaction import save [as 别名]
def transaction( request):
    '''
    View for handling transaction start/stop

    <base_url>/transaction?Action=Start
    <base_url>/transaction?Action=Stop&TransID=<ID>
    '''
    
    # Validate the request
    if request.method != 'GET':
        return HttpResponse( err_not_get(),  status=400)  # Bad request
    
    if not 'Action' in request.GET:
        return HttpResponse( err_missing_param( 'Action'), status=400)  # Bad request
    
    action = request.GET['Action']
    if not (action == 'Start' or action == 'Stop'):
        return HttpResponse( json_err_msg("Expected either 'Start' or 'Stop' for the 'Action' parameter."),
                             status=400)
    if action == 'Start':
        # Start a new transaction
        new_trans = Transaction()
        new_trans.owner = request.user
        new_trans.save()  # Need to call save() so that the id value is generated

        # generate the name and create the directory
        dir_name = os.path.join( settings.TRANSACTION_DIR, request.user.username + '_' + str(new_trans.id))
        os.mkdir(dir_name, 0770)

        # Use setfacl to give the user read, write & execute permissions
        # on the directory we just created    
        permissions = request.user.username + ':rwX'
        proc = subprocess.Popen([settings.SETFACL_BIN, '-m', permissions, dir_name])
        proc.wait()
        if proc.returncode != 0:
            # couldn't set the ACL (maybe this filesystem doesn't support ACL's?)
            # so we need to fail the operation and that means cleaning up after
            # ourselves
            recursive_rm( dir_name)
            new_trans.delete()
            return HttpResponse( json_err_msg( "Cannot start transaction: Failed to set ACL's on transaction directory."),
                                 status=500) # internal server error

        # If we make it here, everything's good - save the transaction object
        # to the DB and return the required JSON        
        new_trans.directory = dir_name
        new_trans.save()
        
        json_out = { }
        json_out['TransID'] = new_trans.id
        json_out['Directory'] = dir_name
        return HttpResponse( json.dumps( json_out))
        
    else:
        # Stop an existing transaction
        # Need to specify the transaction ID
        (trans, error_response) = validate_trans_id( request)
        if error_response != None:
        # TransID didn't validate...
            return error_response
        
        # The transaction is validated - delete the files/directories
        recursive_rm( trans.directory)
        
        # delete the transaction from the db (Django defaults to 'cascaded' deletes,
        # so all we need to do is remove the transaction and everything that was pointing
        # to it (jobs & files) will also be removed
        trans.delete()
        
        return HttpResponse()
开发者ID:neutrons,项目名称:MantidRemote,代码行数:72,代码来源:views.py


注:本文中的models.Transaction.save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。