• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python transaction.Transaction类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中trytond.transaction.Transaction的典型用法代码示例。如果您正苦于以下问题:Python Transaction类的具体用法?Python Transaction怎么用?Python Transaction使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Transaction类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()
开发者ID:Tryton-EvKliD,项目名称:ekd_documents,代码行数:7,代码来源:ekd_documents.py


示例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
开发者ID:Tryton-EvKliD,项目名称:ekd_documents,代码行数:7,代码来源:ekd_invoice_tax.py


示例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
开发者ID:iehoshia,项目名称:training_iesa,代码行数:31,代码来源:account.py


示例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
开发者ID:coopengo,项目名称:commission,代码行数:25,代码来源:commission.py


示例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)
开发者ID:kret0s,项目名称:gnuhealth-live,代码行数:34,代码来源:webdav.py


示例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
开发者ID:priyankajain18,项目名称:nereid,代码行数:33,代码来源:translation.py


示例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))
开发者ID:aleibrecht,项目名称:tryton-modules-ar,代码行数:34,代码来源:statement.py


示例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)
开发者ID:coopengo,项目名称:trytond,代码行数:7,代码来源:table.py


示例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)
开发者ID:coopengo,项目名称:trytond,代码行数:7,代码来源:table.py


示例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;")
开发者ID:fransuar,项目名称:fran_tryton_sale_pos_ar,代码行数:7,代码来源:invoice.py


示例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})
开发者ID:silpol,项目名称:tryton-bef,代码行数:32,代码来源:forecast.py


示例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)
         )
开发者ID:coopengo,项目名称:trytond,代码行数:31,代码来源:table.py


示例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()
开发者ID:kret0s,项目名称:tryton3_8,代码行数:34,代码来源:test_modelsql.py


示例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"})
开发者ID:silpol,项目名称:tryton-bef,代码行数:31,代码来源:health_inpatient.py


示例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
开发者ID:kret0s,项目名称:tryton3_8,代码行数:28,代码来源:hl7_handlers.py


示例16: confirmed

    def confirmed(cls, surgeries):
        surgery_id = surgeries[0]
        Operating_room = Pool().get('gnuhealth.hospital.or')
        cursor = Transaction().cursor

        # Operating Room and end surgery time check
        if (not surgery_id.operating_room or not surgery_id.surgery_end_date):
            cls.raise_user_error("Operating Room and estimated end time  "
            "are needed in order to confirm the surgery")

        or_id = surgery_id.operating_room.id
        cursor.execute("SELECT COUNT(*) \
            FROM gnuhealth_surgery \
            WHERE (surgery_date::timestamp,surgery_end_date::timestamp) \
                OVERLAPS (timestamp %s, timestamp %s) \
              AND (state = %s or state = %s) \
              AND operating_room = CAST(%s AS INTEGER) ",
            (surgery_id.surgery_date,
            surgery_id.surgery_end_date,
            'confirmed', 'in_progress', str(or_id)))
        res = cursor.fetchone()
        if (surgery_id.surgery_end_date <
            surgery_id.surgery_date):
            cls.raise_user_error("The Surgery end date must later than the \
                Start")
        if res[0] > 0:
            cls.raise_user_error('or_is_not_available')
        else:
            cls.write(surgeries, {'state': 'confirmed'})
开发者ID:kret0s,项目名称:gnuhealth-live,代码行数:29,代码来源:health_surgery.py


示例17: __register__

 def __register__(cls, module_name):
     cursor = Transaction().cursor
     # Migration from 1.6: corrected misspelling of ounce (was once)
     cursor.execute("UPDATE ir_model_data "
         "SET fs_id = REPLACE(fs_id, 'uom_once', 'uom_ounce') "
         "WHERE fs_id = 'uom_once' AND module = 'product'")
     super(Uom, cls).__register__(module_name)
开发者ID:Sisouvan,项目名称:ogh,代码行数:7,代码来源:uom.py


示例18: count

    def count(self):
        "Return the count of the Items"
        from trytond.transaction import Transaction

        # XXX: Ideal case should make a copy of Select query
        #
        # https://code.google.com/p/python-sql/issues/detail?id=22
        query = self.query
        query.columns = (Count(Distinct(self.primary_table.id)), )

        cursor = Transaction().connection.cursor()

        # temporarily remove order_by
        order_by = query.order_by
        query.order_by = None
        try:
            cursor.execute(*query)
        finally:
            # XXX: This can be removed when SQL queries can be copied
            # See comment above
            query.order_by = order_by
        res = cursor.fetchone()
        if res:
            return res[0]
        # There can be a case when query return None and then count
        # will be zero
        return 0
开发者ID:fulfilio,项目名称:nereid,代码行数:27,代码来源:pagination.py


示例19: test_float_required

    def test_float_required(self):
        'Test required float'
        pool = Pool()
        FloatRequired = pool.get('test.import_data.float_required')
        transaction = Transaction()

        self.assertEqual(FloatRequired.import_data(['float'],
            [['1.1']]), 1)

        self.assertEqual(FloatRequired.import_data(['float'],
            [['-1.1']]), 1)

        self.assertEqual(FloatRequired.import_data(['float'],
            [['1']]), 1)

        self.assertRaises(UserError, FloatRequired.import_data,
            ['float'], [['']])
        transaction.rollback()

        self.assertEqual(FloatRequired.import_data(['float'],
            [['1.1'], ['2.2']]), 2)

        self.assertRaises(ValueError, FloatRequired.import_data,
            ['float'], [['foo']])

        self.assertEqual(FloatRequired.import_data(['float'],
            [['0']]), 1)

        self.assertEqual(FloatRequired.import_data(['float'],
            [['0.0']]), 1)
开发者ID:coopengo,项目名称:trytond,代码行数:30,代码来源:test_importdata.py


示例20: restore_default_party_lang_from_4_2

    def restore_default_party_lang_from_4_2(cls):
        from trytond.transaction import Transaction
        from sql import Null, Table, Cast
        from sql.operators import Concat
        from trytond.pool import Pool

        TableHandler = backend.get('TableHandler')
        if not TableHandler.table_exist('ir_property'):
            return

        pool = Pool()
        property = Table('ir_property')
        Lang = pool.get('ir.lang')
        field = pool.get('ir.model.field').__table__()
        lang = Lang.__table__()
        cursor = Transaction().connection.cursor()

        query_table = property.join(lang, condition=(
                property.value == Concat('ir.lang,', Cast(lang.id, 'VARCHAR'))
                )).join(field, condition=((property.field == field.id) &
                        (field.name == 'lang')))

        cursor.execute(
            *query_table.select(lang.id, where=property.res == Null))
        result = cursor.fetchone()
        if result:
            result = list(result)
            default_lang = Lang(result[0])
            print('Default Language restored [%s]' % default_lang.rec_name)
            pool.get('party.configuration.party_lang'
                ).create([{'party_lang': default_lang}])
        else:
            print('No default language on party configuration found')
开发者ID:coopengo,项目名称:party,代码行数:33,代码来源:configuration.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python tsWxSize.wxSize函数代码示例发布时间:2022-05-27
下一篇:
Python tools.reduce_ids函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap