本文整理汇总了Python中models.Transaction类的典型用法代码示例。如果您正苦于以下问题:Python Transaction类的具体用法?Python Transaction怎么用?Python Transaction使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Transaction类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:serena617,项目名称:reduction_service,代码行数:32,代码来源:view_util.py
示例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)
开发者ID:jcksncllwy,项目名称:og_challenge_flask,代码行数:7,代码来源:og_challenge_flask.py
示例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()
开发者ID:tovmeod,项目名称:anaf,代码行数:28,代码来源:tests.py
示例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
开发者ID:Hobbyhobbit,项目名称:Stock,代码行数:30,代码来源:views.py
示例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()
开发者ID:kurtraschke,项目名称:WMATA-SmarTrip-Scraper,代码行数:59,代码来源:scraper.py
示例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('/')
开发者ID:swsnider,项目名称:sse-pos,代码行数:8,代码来源:__init__.py
示例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)
开发者ID:alfreda99,项目名称:fullstack_designAGame,代码行数:58,代码来源:api.py
示例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")
开发者ID:MichaelGregory,项目名称:StreetCode,代码行数:58,代码来源:paypal.py
示例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!!")
开发者ID:blupay,项目名称:BLUPAY,代码行数:58,代码来源:views.py
示例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)
开发者ID:cnherald,项目名称:rentalHouseManagement2,代码行数:9,代码来源:rentalManager.py
示例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
开发者ID:tmars,项目名称:DS_CW,代码行数:9,代码来源:xml_rpc.py
示例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)
开发者ID:OspreyX,项目名称:pytrader,代码行数:10,代码来源:TestTransaction.py
示例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)
开发者ID:OspreyX,项目名称:pytrader,代码行数:10,代码来源:TestTransaction.py
示例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
开发者ID:yesudeep,项目名称:maths-school-activation,代码行数:29,代码来源:handlers.py
示例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)
开发者ID:sephtiger,项目名称:txmo-backend,代码行数:12,代码来源:application.py
示例16: deser_tx
def deser_tx(f):
if type(f) is not io.BytesIO:
f = io.BytesIO(f)
from models import Transaction, TxIn, TxOut
tx = Transaction()
tx.version = deser_uint32(f.read(4))
tx.inputs = deser_vector(f, TxIn)
tx.outputs = deser_vector(f, TxOut)
tx.locktime = deser_uint32(f)
return tx
开发者ID:AbraxasCcs,项目名称:blockalchemy,代码行数:12,代码来源:serialize.py
示例17: post
def post(self):
trans = Transaction(id=self.request.get("trans_code"))
trans.trans_code = self.request.get("trans_code")
sender = User.get_by_id(self.request.get("sender_code"))
trans.sender = sender.key.urlsafe()
receiver = User.get_by_id(self.request.get("receiver_code"))
trans.receiver = receiver.key.urlsafe()
trans.description = self.request.get("description")
logging.critical(self.request.get("eda"))
date = datetime.datetime.strptime(self.request.get("eda"), '%m/%d/%Y')
logging.critical(date)
trans.eda = date
p_code = ""
r_code = ""
while True:
p_code = parser_code()
parcel = P.get_by_id(p_code)
if not parcel:
break;
while True:
r_code = receiver_code()
receiver = R.get_by_id(r_code)
if not receiver:
break;
logging.critical(p_code)
logging.critical(r_code)
trans.parser_code = hash_code(p_code, "PARSER")
trans.receiver_code = hash_code(r_code, "RECEIVER")
trans.put()
""" save transaction for PARSEL code """
p = P(id=p_code)
p.codes = p_code
p.trans_key = trans.key.urlsafe()
p.put()
""" ---------------------------------- """
""" save transaction for RECEIVER code """
r = R(id=r_code)
r.codes = r_code
r.trans_key = trans.key.urlsafe()
r.put()
""" ---------------------------------- """
self.redirect(self.uri_for('www-login', success="Added!."))
开发者ID:,项目名称:,代码行数:52,代码来源:
示例18: createTransaction
def createTransaction(self, props):
tx = Transaction( method = 'PayPal',
donor = props['donor'],
client = props['client'],
txID = props['txn_id'],
paymentDate = urllib.unquote(props['payment_date']).replace('+', ' '),
amount = float(props['mc_gross']),
fee = float(props['mc_fee']) ,
paymentStatus = props['payment_status'],
note = urllib.unquote(props['item_name']).replace('+', ' '),
fulfilled = False
)
tx.put()
return tx
开发者ID:MayaLi,项目名称:StreetCode,代码行数:14,代码来源:paypal.py
示例19: init
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,代码行数:50,代码来源:__init__.py
示例20: get_transactions
def get_transactions(self, account_number):
db_account_id = self.get_accountid(account_number)
trans = Transaction.select().where(Transaction.ACCOUNTID==db_account_id)
results = []
for row in trans:
results.append(row)
return results
开发者ID:ssuppe,项目名称:MMexImporter,代码行数:7,代码来源:MMexDB.py
注:本文中的models.Transaction类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论