本文整理汇总了Python中trytond.transaction.Transaction类的典型用法代码示例。如果您正苦于以下问题:Python Transaction类的具体用法?Python Transaction怎么用?Python Transaction使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Transaction类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: default_date_account
def default_date_account(self ):
context = Transaction().context
if context.get('date_account'):
return context.get('date_account')
elif context.get('current_date'):
return context.get('current_date')
return datetime.datetime.now()
示例2: default_currency_digits
def default_currency_digits(self):
company_obj = self.pool.get("company.company")
context = Transaction().context
if context.get("company"):
company = company_obj.browse(context["company"])
return company.currency.digits
return 2
示例3: get_expenses
def get_expenses(self):
pool = Pool()
Date = pool.get('ir.date')
AccountType = pool.get('account.account.type')
today = Date.today()
transaction = Transaction()
context = Transaction().context
total_expense = expense = Decimal('0.0')
if self.is_consolidated:
companies = context.get('companies',[])
for company in context.get('companies', []):
with transaction.set_context(company=company['id']):
expense = Decimal('0.0')
expenses = AccountType.search([('company','=',company['id']),
('name','=','GASTOS FINANCIEROS')
])
if len(expenses)==1:
expense = expenses[0].amount * Decimal('1.0')
total_expense += expense
return total_expense
else:
company = Transaction().context.get('company')
expense = Decimal('0.0')
expenses = AccountType.search([('company','=',company),
('name','=','GASTOS FINANCIEROS')])
if len(expenses)==1:
expense = expenses[0].amount * Decimal('1.0')
return expense
示例4: get_pending_amount
def get_pending_amount(cls, agents, name):
pool = Pool()
Commission = pool.get('commission')
commission = Commission.__table__()
cursor = Transaction().connection.cursor()
ids = [a.id for a in agents]
amounts = dict.fromkeys(ids, None)
for sub_ids in grouped_slice(ids):
where = reduce_ids(commission.agent, sub_ids)
where &= commission.invoice_line == Null
query = commission.select(commission.agent, Sum(commission.amount),
where=where,
group_by=commission.agent)
cursor.execute(*query)
amounts.update(dict(cursor.fetchall()))
digits = cls.pending_amount.digits
exp = Decimal(str(10.0 ** -digits[1]))
for agent_id, amount in amounts.items():
if amount:
# SQLite uses float for SUM
if not isinstance(amount, Decimal):
amount = Decimal(str(amount))
amounts[agent_id] = amount.quantize(exp)
return amounts
示例5: get_creationdate
def get_creationdate(cls, uri, cache=None):
Party = Pool().get('party.party')
party = Party.__table__()
party_id = cls.vcard(uri)
cursor = Transaction().cursor
if party_id is None:
raise DAV_NotFound
if party_id:
if cache is not None:
cache.setdefault('_contact', {})
ids = cache['_contact'].keys()
if party_id not in ids:
ids.append(party_id)
elif 'creationdate' in cache['_contact'][party_id]:
return cache['_contact'][party_id]['creationdate']
else:
ids = [party_id]
res = None
for sub_ids in grouped_slice(ids):
red_sql = reduce_ids(party.id, sub_ids)
cursor.execute(*party.select(party.id,
Extract('EPOCH', party.create_date),
where=red_sql))
for party_id2, date in cursor.fetchall():
if party_id2 == party_id:
res = date
if cache is not None:
cache['_contact'].setdefault(party_id2, {})
cache['_contact'][party_id2]['creationdate'] = date
if res is not None:
return res
return super(Collection, cls).get_creationdate(uri, cache=cache)
示例6: get_translation_4_nereid
def get_translation_4_nereid(cls, module, ttype, lang, source):
"Return translation for source"
ttype = unicode(ttype)
lang = unicode(lang)
source = unicode(source)
cache_key = (lang, ttype, source, module)
trans = cls._nereid_translation_cache.get(cache_key, -1)
if trans != -1:
return trans
cursor = Transaction().cursor
table = cls.__table__()
where = (
(table.lang == lang) &
(table.type == ttype) &
(table.value != '') &
(table.value != None) &
(table.fuzzy == False) &
(table.src == source)
)
if module is not None:
where &= (table.module == module)
cursor.execute(*table.select(table.value, where=where))
res = cursor.fetchone()
if res:
cls._nereid_translation_cache.set(cache_key, res[0])
return res[0]
else:
cls._nereid_translation_cache.set(cache_key, False)
return None
示例7: __register__
def __register__(cls, module_name):
TableHandler = backend.get('TableHandler')
cursor = Transaction().cursor
sql_table = cls.__table__()
# Migration from 1.8: new field company
table = TableHandler(cursor, cls, module_name)
company_exist = table.column_exist('company')
super(Statement, cls).__register__(module_name)
# Migration from 1.8: fill new field company
if not company_exist:
offset = 0
limit = cursor.IN_MAX
statements = True
while statements:
statements = cls.search([], offset=offset, limit=limit)
offset += limit
for statement in statements:
cls.write([statement], {
'company': statement.journal.company.id,
})
table = TableHandler(cursor, cls, module_name)
table.not_null_action('company', action='add')
# Migration from 3.2: remove required on start/end balance
table.not_null_action('start_balance', action='remove')
table.not_null_action('end_balance', action='remove')
# Migration from 3.2: add required name
cursor.execute(*sql_table.update([sql_table.name],
[sql_table.id.cast(cls.name.sql_type().base)],
where=sql_table.name == None))
示例8: alter_type
def alter_type(self, column_name, column_type):
cursor = Transaction().connection.cursor()
cursor.execute('ALTER TABLE `%s` '
'MODIFY COLUMN `%s` %s'
% (self.table_name, column_name,
self._column_definition(column_name, typname=column_type)))
self._update_definitions(columns=True)
示例9: db_default
def db_default(self, column_name, value):
cursor = Transaction().connection.cursor()
cursor.execute('ALTER TABLE `%s` '
'MODIFY COLUMN `%s` %s'
% (self.table_name, column_name,
self._column_definition(column_name, default=value)))
self._update_definitions(columns=True)
示例10: __register__
def __register__(cls, z_fix__invoice_ar__sale_pos):
#super(AfipWSTransaction, cls).__register__(z_fix__invoice_ar__sale_pos)
TableHandler = backend.get('TableHandler')
cursor = Transaction().cursor
table = TableHandler(cursor, cls, z_fix__invoice_ar__sale_pos)
cursor.execute("ALTER TABLE account_invoice_ar_afip_transaction\
DROP CONSTRAINT IF EXISTS account_invoice_ar_afip_transaction_invoice_fkey;")
示例11: check_date_overlap
def check_date_overlap(self):
cursor = Transaction().cursor
if self.state != "done":
return True
cursor.execute(
"SELECT id "
"FROM stock_forecast "
"WHERE ((from_date <= %s AND to_date >= %s) "
"OR (from_date <= %s AND to_date >= %s) "
"OR (from_date >= %s AND to_date <= %s)) "
"AND warehouse = %s "
"AND destination = %s "
"AND state = 'done' "
"AND company = %s "
"AND id != %s",
(
self.from_date,
self.from_date,
self.to_date,
self.to_date,
self.from_date,
self.to_date,
self.warehouse.id,
self.destination.id,
self.company.id,
self.id,
),
)
forecast_id = cursor.fetchone()
if forecast_id:
second = self.__class__(forecast_id[0])
self.raise_user_error("date_overlap", {"first": self.rec_name, "second": second.rec_name})
示例12: column_rename
def column_rename(self, old_name, new_name, exception=False):
cursor = Transaction().connection.cursor()
if self.column_exist(old_name) and not self.column_exist(new_name):
temp_table = "_temp_%s" % self.table_name
TableHandler.table_rename(self.table_name, temp_table)
new_table = TableHandler(self._model, history=self.history)
for column, (notnull, hasdef, size, typname) in self._columns.iteritems():
if column == old_name:
column = new_name
new_table.add_raw_column(column, typname, False, field_size=size)
new_columns = new_table._columns.keys()
old_columns = [x if x != old_name else new_name for x in new_columns]
cursor.execute(
(
'INSERT INTO "%s" ('
+ ",".join('"%s"' % x for x in new_columns)
+ ") SELECT "
+ ",".join('"%s"' % x for x in old_columns)
+ " "
+ 'FROM "%s"'
)
% (self.table_name, temp_table)
)
cursor.execute('DROP TABLE "%s"' % temp_table)
self._update_definitions()
elif exception and self.column_exist(new_name):
raise Exception(
"Unable to rename column %s.%s to %s.%s: "
"%s.%s already exist!"
% (self.table_name, old_name, self.table_name, new_name, self.table_name, new_name)
)
示例13: test_check_timestamp
def test_check_timestamp(self):
'Test check timestamp'
pool = Pool()
ModelsqlTimestamp = pool.get('test.modelsql.timestamp')
transaction = Transaction()
# cursor must be committed between each changes otherwise NOW() returns
# always the same timestamp.
cursor = transaction.cursor
record, = ModelsqlTimestamp.create([{}])
cursor.commit()
timestamp = ModelsqlTimestamp.read([record.id],
['_timestamp'])[0]['_timestamp']
if backend.name() in ('sqlite', 'mysql'):
# timestamp precision of sqlite is the second
time.sleep(1)
ModelsqlTimestamp.write([record], {})
cursor.commit()
transaction.timestamp[str(record)] = timestamp
self.assertRaises(ConcurrencyException,
ModelsqlTimestamp.write, [record], {})
transaction.timestamp[str(record)] = timestamp
self.assertRaises(ConcurrencyException,
ModelsqlTimestamp.delete, [record])
transaction.timestamp.pop(str(record), None)
ModelsqlTimestamp.write([record], {})
cursor.commit()
ModelsqlTimestamp.delete([record])
cursor.commit()
示例14: confirmed
def confirmed(cls, registrations):
registration_id = registrations[0]
Bed = Pool().get("gnuhealth.hospital.bed")
cursor = Transaction().cursor
bed_id = registration_id.bed.id
cursor.execute(
"SELECT COUNT(*) \
FROM gnuhealth_inpatient_registration \
WHERE (hospitalization_date::timestamp,discharge_date::timestamp) \
OVERLAPS (timestamp %s, timestamp %s) \
AND (state = %s or state = %s) \
AND bed = CAST(%s AS INTEGER) ",
(
registration_id.hospitalization_date,
registration_id.discharge_date,
"confirmed",
"hospitalized",
str(bed_id),
),
)
res = cursor.fetchone()
if registration_id.discharge_date.date() < registration_id.hospitalization_date.date():
cls.raise_user_error(
"The Discharge date must later than the \
Admission"
)
if res[0] > 0:
cls.raise_user_error("bed_is_not_available")
else:
cls.write(registrations, {"state": "confirmed"})
Bed.write([registration_id.bed], {"state": "reserved"})
示例15: wrap
def wrap(self, *args, **kwargs):
message_res = met(self, *args, **kwargs)
if self.logger_enabled:
message_req = self.incoming_message
logger.debug("Saving transition:\nIN: %s\nOUT: %s\nHandler: %s\n" % (message_req, message_res,
self.__class__.__name__))
transaction = Transaction()
logger.debug("Starting db transaction for domain:%s" % self.pool_manager.get_domain())
transaction.start(self.pool_manager.get_domain(), 0)
logger.debug("Connecting to table")
hl7_message_logger = self.pool_manager.get_table("hl7.message_logger")
logger.debug("Preparing query for table:::%s" % hl7_message_logger)
cursor = transaction.cursor
insert_columns = [hl7_message_logger.create_uid, hl7_message_logger.create_date,
hl7_message_logger.creation_date, hl7_message_logger.request,
hl7_message_logger.response, hl7_message_logger.handler_module]
insert_values = [transaction.user, Now(), Now(), message_req, message_res[1:-2], self.__class__.__name__]
cursor.execute(*hl7_message_logger.insert(insert_columns, [insert_values]))
cursor.execute("commit")
logger.debug("Query executed")
transaction.stop()
return message_res