本文整理汇总了Python中models.Transaction类的典型用法代码示例。如果您正苦于以下问题:Python Transaction类的具体用法?Python Transaction怎么用?Python Transaction使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Transaction类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: transaction
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
示例2: scrub
def scrub():
if request.method == "POST":
file = request.files["file"]
if file:
transactions = Transaction.from_csv_file(file)
report = Transaction.transaction_report(transactions)
return jsonify(**report)
示例3: test_model_transaction
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()
示例4: create_transaction
def create_transaction():
''' Creates a transaction for the user's shopping cart. Apparently, adding
relations to transient transactions somehow automatically adds them to the
current session. As we usually don't want to commit semi-complete
transactions, DB modifications are prepent with session.rollback(). '''
ta = Transaction()
lending = session_or_empty('lend')
buying = session_or_empty('buy')
ta.group = session_or_empty('group')
if ta.group == []:
ta.group = 'int'
for id in lending:
item = Item.query.get(id)
ta.lend[id] = Lend(item, lending[id])
for id in buying:
item = Item.query.get(id)
ta.buy[id] = Buy(item, buying[id])
ta.date_start = session_or_empty('date_start')
ta.date_end = session_or_empty('date_end')
ta.name = session_or_empty('name')
ta.email = session_or_empty('email')
ta.tel = session_or_empty('tel')
g.ta = ta
示例5: scrapeCard
def scrapeCard(br, session, cardID, cardSerial):
#follows link to View Card Summary page for a particular card
response1 = br.follow_link(url_regex=r"CardSummary.aspx\?card_id=" + cardID).read()
#follows link to View Usage History page for a particular card
response1 = br.follow_link(text_regex=r"View Usage History").read()
br.select_form(name="aspnetForm")
response1 = br.submit().read()
br.select_form(name="aspnetForm")
#transaction status either 'All' or 'Successful' or 'Failed Autoloads';
#'All' includes every succesful transaction including failed (card didn't swipe or error)
br["ctl00$MainContent$ddlTransactionStatus"] = ["All"]
br.submit()
#wmata only started posting data in 2010, pulls all available months
for year in xrange(2010, 2011+1):
for month in xrange(1, 12+1):
time_period = ("%d%02d" % (year, month))
print "\t", time_period
#opens link to 'print' version of usage page for easier extraction
br.open("https://smartrip.wmata.com/Card/CardUsageReport2.aspx?card_id=" +
cardID + "&period=M&month=" + time_period)
response1 = br.follow_link(text_regex=r"Print Version").read()
#extracts data from html table, writes to csv
soup = BeautifulSoup.BeautifulSoup(response1)
table = soup.find('table', {'class': 'reportTable'})
if table is None:
continue
rows = table.findAll('tr')
it = iter(rows)
try:
while True:
cols = it.next().findAll('td')
if len(cols) == 0:
continue #ignore blank rows
rowspan = int(cols[0].get('rowspan', '1'))
parsedCols = [td.find(text=True) for td in cols]
(sequence, timestamp, description, operator, entry, exit) = parsedCols[0:6]
purses = []
purses.append(parsedCols[6:9])
if rowspan > 1:
for i in xrange(1, rowspan):
cols = it.next().findAll('td')
purses.append([td.find(text=True) for td in cols])
txn = Transaction(sequence, timestamp, description, operator, entry, exit, purses)
txn.card_id = cardID
txn.card_serial = cardSerial
session.add(txn)
except StopIteration:
pass
session.commit()
示例6: logout
def logout(self, **kwargs):
if 'transaction_key' in self.session:
try:
Transaction2.get(Key(encoded=self.session['transaction_key'])).delete()
except:
Transaction.get(Key(encoded=self.session['transaction_key'])).delete()
self.users.logout()
self.redirect('/')
示例7: make_guess
def make_guess(self, request):
"""Guess a letter. Returns a game state with message"""
game = get_by_urlsafe(request.urlsafe_game_key, Game)
if game.game_over:
raise endpoints.BadRequestException(
'Game already over!')
if game.game_cancelled:
raise endpoints.BadRequestException(
'Game has been cancelled!')
if len(request.guess) > 1:
raise endpoints.BadRequestException(
'You can only guess one letter!')
if not request.guess.isalpha():
raise endpoints.BadRequestException(
'The guess must be a letter!')
# Determine if guess is correct. If so, update score
score = Score.query(ancestor=game.key).get()
if request.guess in game.game_word:
msg = 'You guessed right. The game word does contain the letter '\
+ request.guess + '.'
# find all correctly guess letters in the game word and
# set those letters in the guess string
for index, char in enumerate(game.game_word):
if char == request.guess:
game.correct_guesses[index] = char
score.points += 1
else:
msg = 'Sorry, the game word does not contain the letter '\
+ request.guess + '.'
game.hangman.append(STICK_MAN_PARTS[game.attempts_remaining-1])
game.attempts_remaining -= 1
game.incorrect_guesses.append(request.guess)
if ''.join(game.correct_guesses) == game.game_word:
game.game_over = True
score.points += 30
score.won = True
msg = 'You win!'
elif game.attempts_remaining < 1:
game.game_over = True
msg = msg + 'Sorry, Game over!'
game.put()
score.put()
# Record the transaction
trans = Transaction(date=datetime.today(),
game=game.key,
guess=request.guess,
result=msg)
trans.put()
return game.to_form(msg)
示例8: get
def get(self, client):
# Get the transaction id, tx=blahblahblah
trans_id = self.request.get("tx")
# Confgure POST args
args = {}
# Specify the paypal command
args["cmd"] ="_notify-synch"
args["tx"] = trans_id
args["at"] = settings.PAYPAL_PDT_KEY
args = urllib.urlencode(args)
try:
# Do a post back to validate
# the transaction data
status = urlfetch.fetch(url = settings.PAYPAL_URL,
method = urlfetch.POST,
payload = args).content
except:
self.response.out.write("POST Failed")
# Check for SUCCESS at the start of the response
lines = status.split(' ')
if lines[0] == 'SUCCESS':
lines = line[1:]
props = {}
for line in lines:
(key, value) = line.split('=')
props[key] = value
# Check other transaction details here like
# payment_status etc..
# TODO Update donation transaction in streetcodes
client = Client.all().filter('shortCode =', props['item_number']).get()
donor = Donor.all().filter('email =', props['email']).get()
if donor is None:
donor = Donor()
donor.name = "%s %s" % (props['first'], props['last'])
donor.email = props['email']
donor.put()
tx = Transaction(method='PayPal',
donor=donor,
client=client,
amount=props['amount'])
tx.put()
# redirect user to thank you screen "/client_short_code#thanks"
self.response.out.write('<script> window.location = "/'+ client + '#thanks"; </script>')
# DEBUG code
# self.response.out.write("OK<br>")
# self.response.out.write(urllib.unquote(status))
else:
self.response.out.write("Failed")
示例9: get_post_function
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+'®</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+'®</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+'®</b>')
except Customer.DoesNotExist:
return HttpResponseForbidden("Forbidden!!, Customer does not exist!!")
示例10: post
def post(self):
self.response.headers['Content-Type'] = 'application/json'
jsonString = self.request.body
data = simplejson.loads(jsonString) #Decoding JSON
transaction = Transaction()
transaction.processTransaction(data)
response = {'payRentSuccessNotice':'Congratulations, you have paid the rent!'}
json_response= simplejson.dumps(response)
return self.response.out.write(json_response)
示例11: create_transaction
def create_transaction(client_id, recipient_number, amount):
try:
recipient = Bill.objects.get(number=recipient_number)
except:
return [recipient_number, amount]
trans = Transaction()
trans.create(client_id, recipient, amount)
return trans.code
示例12: test_transaction_value_buy
def test_transaction_value_buy(self):
t = Transaction(units=10, price=5, date=None)
self.assertEqual(t.value(), 50)
self.assertEqual(t.value(transaction_cost_base=5), 55)
self.assertAlmostEqual(t.value(transaction_cost_base=5, transaction_cost_perc=0.10), 60)
self.assertAlmostEqual(t.value(transaction_cost_perc=0.15), 57.5)
示例13: test_transaction_value_sell
def test_transaction_value_sell(self):
t = Transaction(units=-10, price=5, date=None)
self.assertEqual(t.value(), -50)
self.assertEqual(t.value(transaction_cost_base=5), -45)
self.assertAlmostEqual(t.value(transaction_cost_base=5, transaction_cost_perc=0.10), -40)
self.assertAlmostEqual(t.value(transaction_cost_perc=0.15), -42.5)
示例14: post
def post(self):
data = flatten_arguments(self.request.arguments)
from models import Transaction, Invoice
from pprint import pformat
invoice_id = data.get('invoice')
if invoice_id:
invoice = Invoice.get_by_id(int(invoice_id, 10))
txn = Transaction(invoice=invoice)
txn.identifier = data.get('txn_id')
txn.subscription_id = data.get("subscr_id")
txn.transaction_type = data.get('txn_type')
txn.currency = data.get('mc_currency')
txn.amount = data.get('mc_gross', data.get('mc_amount3'))
txn.data = pformat(data)
txn.put()
if self.verify(data):
r = self.process(data, txn=txn, invoice=invoice)
else:
r = self.process_invalid(data, txn=txn, invoice=invoice)
if r:
self.write(r)
else:
self.write('Nothing to see here.')
else:
# error. invoice id was not found.
pass
示例15: post
def post(self):
company = Company.query.get(request.form['company_id'])
if company is None:
return jsonify(message='Company does not exists')
transaction = Transaction()
transaction.company_id = company.id
transaction.type = request.form['type']
transaction.amount = request.form['amount']
transaction.date = request.form['date']
db.session.add(transaction)
db.session.commit()
return jsonify(transaction.serialize)