How to use the trytond.config.config.getint function in trytond

To help you get started, we’ve selected a few trytond examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github tryton / trytond / trytond / backend / postgresql / View on Github external
def list(self, hostname=None):
        now = time.time()
        timeout = config.getint('session', 'timeout')
        res = self.__class__._list_cache.get(hostname)
        timestamp = self.__class__._list_cache_timestamp.get(hostname, now)
        if res and abs(timestamp - now) < timeout:
            return res

        connection = self.get_connection()
            cursor = connection.cursor()
            cursor.execute('SELECT datname FROM pg_database '
                'WHERE datistemplate = false ORDER BY datname')
            res = []
            for db_name, in cursor:
                    with connect(**self._connection_params(db_name)
                            ) as conn:
                        if self._test(conn, hostname=hostname):
github tryton / trytond / trytond / res / View on Github external
def get_login(cls, login, parameters):
        Return user id if password matches
        LoginAttempt = Pool().get('res.user.login.attempt')
        count_ip = LoginAttempt.count_ip()
        if count_ip > config.getint(
                'session', 'max_attempt_ip_network', default=300):
            # Do not add attempt as the goal is to prevent flooding
            raise RateLimitException()
        count = LoginAttempt.count(login)
        if count > config.getint('session', 'max_attempt', default=5):
            raise RateLimitException()
        Transaction().atexit(time.sleep, random.randint(0, 2 ** count - 1))
        for methods in config.get(
                'session', 'authentications', default='password').split(','):
            user_ids = set()
            for method in methods.split('+'):
                    func = getattr(cls, '_login_%s' % method)
                except AttributeError:
          'Missing login method: %s', method)
                user_ids.add(func(login, parameters))
                if len(user_ids) != 1 or not all(user_ids):
            if len(user_ids) == 1 and all(user_ids):
github tryton / trytond / trytond / model / View on Github external
from import (
    domain_inversion, parse as domain_parse)
from trytond.pyson import PYSONEncoder, PYSONDecoder, PYSON
from trytond.const import OPERATORS
from trytond.config import config
from trytond.i18n import gettext, lazy_gettext
from trytond.transaction import Transaction
from trytond.pool import Pool
from trytond.cache import LRUDict, LRUDictTransaction, freeze
from trytond.rpc import RPC
from .modelview import ModelView
from .descriptors import dualmethod

__all__ = ['ModelStorage', 'EvalEnvironment']
_cache_record = config.getint('cache', 'record')
_cache_field = config.getint('cache', 'field')

class AccessError(UserError):

class ImportDataError(UserError):

class ValidationError(UserError):

class DomainValidationError(ValidationError):
github tryton / trytond / trytond / View on Github external
# This file is part of Tryton.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import logging
import time
from collections import defaultdict
from threading import local
from sql import Flavor

from trytond.config import config

_cache_model = config.getint('cache', 'model')
logger = logging.getLogger(__name__)

class _AttributeManager(object):
    Manage Attribute of transaction

    def __init__(self, **kwargs):
        self.kwargs = kwargs

    def __enter__(self):
        return Transaction()

    def __exit__(self, type, value, traceback):
        for name, value in self.kwargs.items():
github tryton / trytond / trytond / ir / View on Github external
def run(cls, db_name):'cron started for "%s"', db_name)
        now =
        retry = config.getint('database', 'retry')
        with Transaction().start(db_name, 0) as transaction:
            transaction.database.lock(transaction.connection, cls._table)
            crons =['OR',
                    ('next_call', '<=', now),
                    ('next_call', '=', None),

            for cron in crons:
      "Run cron %s",
                for count in range(retry, -1, -1):
                    if count != retry:
                        time.sleep(0.02 * (retry - count))
                        cron.next_call = cron.compute_next_call(now)
github tryton / trytond / trytond / backend / postgresql / View on Github external
from sql import Flavor, Cast, For
from sql.functions import Function
from sql.operators import BinaryOperator

from trytond.backend.database import DatabaseInterface, SQLType
from trytond.config import config, parse_uri
from import is_gevent_monkey_patched

__all__ = ['Database', 'DatabaseIntegrityError', 'DatabaseOperationalError']

logger = logging.getLogger(__name__)

os.environ['PGTZ'] = os.environ.get('TZ', '')
_timeout = config.getint('database', 'timeout')
_minconn = config.getint('database', 'minconn', default=1)
_maxconn = config.getint('database', 'maxconn', default=64)
_default_name = config.get('database', 'default_name', default='template1')

def unescape_quote(s):
    if s.startswith('"') and s.endswith('"'):
        return s.strip('"').replace('""', '"')
    return s

def replace_special_values(s, **mapping):
    for name, value in mapping.items():
        s = s.replace('$' + name, value)
    return s
github tryton / trytond / trytond / View on Github external
NotImplemented as NotImplementedException, BadRequest)

from trytond import backend
from trytond.wsgi import app
from trytond.transaction import Transaction
from trytond.protocols.jsonrpc import JSONEncoder, JSONDecoder
from trytond.config import config
from import resolve

logger = logging.getLogger(__name__)

_db_timeout = config.getint('database', 'timeout')
_cache_timeout = config.getint('bus', 'cache_timeout')
_select_timeout = config.getint('bus', 'select_timeout')
_long_polling_timeout = config.getint('bus', 'long_polling_timeout')
_allow_subscribe = config.getboolean('bus', 'allow_subscribe')
_url_host = config.get('bus', 'url_host')
_web_cache_timeout = config.getint('web', 'cache_timeout')

class _MessageQueue:

    Message = collections.namedtuple('Message', 'channel content timestamp')

    def __init__(self, timeout):
        self._lock = threading.Lock()
        self._timeout = timeout
        self._messages = []

    def append(self, channel, element):
github tryton / trytond / trytond / protocols / View on Github external
if rpc.fresh_session and session:
        context = {'_request': request.context}
        if not security.check_timeout(
                pool.database_name, user, session, context=context):

    log_message = '%s.%s(*%s, **%s) from %s@%s/%s'
    username = request.authorization.username
    if isinstance(username, bytes):
        username = username.decode('utf-8')
    log_args = (
        obj, method, args, kwargs, username, request.remote_addr, request.path), *log_args)

    retry = config.getint('database', 'retry')
    for count in range(retry, -1, -1):
        if count != retry:
            time.sleep(0.02 * (retry - count))
        with Transaction().start(pool.database_name, user,
                readonly=rpc.readonly) as transaction:
                c_args, c_kwargs, transaction.context, transaction.timestamp \
                    = rpc.convert(obj, *args, **kwargs)
                transaction.context['_request'] = request.context
                meth = getattr(obj, method)
                if (rpc.instantiate is None
                        or not is_instance_method(obj, method)):
                    result = rpc.result(meth(*c_args, **c_kwargs))
                    assert rpc.instantiate == 0
                    inst = c_args.pop(0)
github tryton / trytond / trytond / ir / View on Github external
def check(cls, user, key, domain=None):
        Check user key against max_age and delete old one.
        Return True if key is still valid, False if the key is expired and None
        if the key does not exist.
        now =
        timeout = datetime.timedelta(
            seconds=config.getint('session', 'max_age'))
        sessions =[
                ('create_uid', '=', user),
                domain or [],
        find = None
        to_delete = []
        for session in sessions:
            if abs(session.create_date - now) < timeout:
                if session.key == key:
                    find = True
                if find is None and session.key == key:
                    find = False
        return find