예제 #1
0
파일: config.py 프로젝트: sivadax/proteus
    def __init__(self, database=None, user='******', config_file=None):
        super(TrytondConfig, self).__init__()
        if not database:
            database = os.environ.get('TRYTOND_DATABASE_URI')
        else:
            os.environ['TRYTOND_DATABASE_URI'] = database
        if not config_file:
            config_file = os.environ.get('TRYTOND_CONFIG')
        from trytond.config import config
        config.update_etc(config_file)
        from trytond.pool import Pool
        from trytond.transaction import Transaction
        self.database = database
        database_name = None
        if database:
            uri = urlparse.urlparse(database)
            database_name = uri.path.strip('/')
        if not database_name:
            database_name = os.environ['DB_NAME']
        self.database_name = database_name
        self._user = user
        self.config_file = config_file

        Pool.start()
        self.pool = Pool(database_name)
        self.pool.init()

        with Transaction().start(self.database_name, 0) as transaction:
            User = self.pool.get('res.user')
            transaction.context = self.context
            self.user = User.search([
                ('login', '=', user),
                ], limit=1)[0].id
            with transaction.set_user(self.user):
                self._context = User.get_preferences(context_only=True)
예제 #2
0
    def __call__(self, environ, start_response):
        if not self.loaded:
            config.update_etc(environ.get('trytond.config'))
            logconf = config.get('optional', 'logconf')
            if logconf:
                os.environ['TRYTOND_LOGGING_CONFIG'] = logconf

            from trytond.application import app
            self.app = app
            self.loaded = True
        return self.app.wsgi_app(environ, start_response)
예제 #3
0
    def load_backend(self):
        """
        This method loads the configuration file if specified and
        also connects to the backend, initialising the pool on the go
        """
        if self.tryton_configfile is not None:
            warnings.warn(DeprecationWarning(
                'TRYTON_CONFIG configuration will be deprecated in future.'
            ))
            config.update_etc(self.tryton_configfile)

        # Load and initialise pool
        Database = backend.get('Database')
        self._database = Database(self.database_name).connect()
        self._pool = Pool(self.database_name)
        self._pool.init()
예제 #4
0
    def load_backend(self):
        """
        This method loads the configuration file if specified and
        also connects to the backend, initialising the pool on the go
        """
        if self.tryton_configfile is not None:
            warnings.warn(
                DeprecationWarning(
                    'TRYTON_CONFIG configuration will be deprecated in future.'
                ))
            config.update_etc(self.tryton_configfile)

        # Load and initialise pool
        Database = backend.get('Database')
        self._database = Database(self.database_name).connect()
        self._pool = Pool(self.database_name)
        self._pool.init()
예제 #5
0
def _load(database, scenario, lang_codes=None, config_file=None):
    os.environ['TRYTOND_DATABASE_URI'] = 'postgresql://'
    os.environ['DB_NAME'] = database

    if config_file:
        from trytond.config import config
        config.update_etc(config_file)

    _create_db(database, lang_codes=lang_codes, config_file=config_file)

    import trytond.tests.test_tryton
    suite = trytond.tests.test_tryton.suite()
    suite.addTests(
        doctest.DocFileSuite(scenario, module_relative=False,
                             encoding='utf-8'))

    unittest.TextTestRunner(verbosity=True).run(suite)
예제 #6
0
def _create_db(database, lang_codes=None, config_file=None):
    """
    Create and set active languages if database doesn't exists.
    Otherwise, do nothing.
    """
    os.environ['TRYTOND_DATABASE_URI'] = 'postgresql://'
    os.environ['DB_NAME'] = database

    if config_file:
        from trytond.config import config
        config.update_etc(config_file)

    from trytond.tests.test_tryton import db_exist, create_db
    if not db_exist():
        create_db()
        if _set_active_languages(database, lang_codes=lang_codes):
            _update_all(database)
        return True
    return False
예제 #7
0
    def init(cls):
        r"""
        Initialize a Tryton database.

        Should be called only once. Updates the tryton config and writes the
        configured number of retries into the class attribute _retry.

        Configuration via class attributes, e.g.::

            >>> Tdb._db = 'db'
            >>> Tdb._configfile = '/path/to/configfile'
            >>> Tdb._company = 1
            >>> Tdb._user = '******'
            >>> Tdb.init()

        Expects class attributes _db, _configfile, _company and _user to be
        set.
        """
        config.update_etc(str(cls._configfile))
        cls._retry = config.getint('database', 'retry')
        with Transaction().start(str(cls._db), int(cls._user), readonly=True):
            Pool().init()
예제 #8
0
파일: config.py 프로젝트: coopengo/proteus
    def __init__(self, database=None, user='******', config_file=None):
        super(TrytondConfig, self).__init__()
        if not database:
            database = os.environ.get('TRYTOND_DATABASE_URI')
        else:
            os.environ['TRYTOND_DATABASE_URI'] = database
        if not config_file:
            config_file = os.environ.get('TRYTOND_CONFIG')
        from trytond.config import config
        config.update_etc(config_file)
        from trytond.pool import Pool
        from trytond.cache import Cache
        from trytond.transaction import Transaction
        self.database = database
        database_name = None
        if database:
            uri = urlparse.urlparse(database)
            database_name = uri.path.strip('/')
        if not database_name:
            database_name = os.environ['DB_NAME']
        self.database_name = database_name
        self._user = user
        self.config_file = config_file

        Pool.start()
        self.pool = Pool(database_name)
        self.pool.init()

        with Transaction().start(self.database_name, 0) as transaction:
            Cache.clean(database_name)
            User = self.pool.get('res.user')
            transaction.context = self.context
            self.user = User.search([
                ('login', '=', user),
                ], limit=1)[0].id
            with transaction.set_user(self.user):
                self._context = User.get_preferences(context_only=True)
            Cache.resets(database_name)
예제 #9
0
    Implementation of the celery app

    This module is named celery because of the way celery workers lookup
    the app when `--proj` argument is passed to the worker. For more details
    see the celery documentation at:
    http://docs.celeryproject.org/en/latest/getting-started/next-steps.html#about-the-app-argument
"""
from __future__ import absolute_import

import os

from celery import Celery
from trytond.config import config

config.update_etc()


broker_url = config.get('async', 'broker_url')
backend_url = config.get('async', 'backend_url')

app = Celery(
    'trytond_async',
    broker=broker_url or os.environ.get('TRYTOND_ASYNC__BROKER_URL'),
    backend=backend_url or os.environ.get('TRYTOND_ASYNC__BACKEND_URL'),
    include=['trytond_async.tasks']
)

app.conf.update(
    CELERY_TASK_RESULT_EXPIRES=3600,
    CELERY_TASK_SERIALIZER='tryson',
예제 #10
0
#!/usr/bin/env python
import os

from nereid import Nereid
from werkzeug.contrib.sessions import FilesystemSessionStore
from nereid.contrib.locale import Babel
from nereid.sessions import Session
from trytond.config import config
config.update_etc()

CWD = os.path.abspath(os.path.dirname(__file__))

CONFIG = dict(

    # The name of database
    DATABASE_NAME=os.environ.get('TRYTOND_DB_NAME'),

    # If the application is to be configured in the debug mode
    DEBUG=True,

    # The location where the translations of this template are stored
    TRANSLATIONS_PATH='i18n',

    # Secret Key: Replace this with something random
    # A good way to generate such a number would be
    #
    # >>> import os
    # >>> os.urandom(20)
    #
    SECRET_KEY='\xcd\x04}\x8d\\j-\x98b\xf2')
예제 #11
0
                    default=True,
                    help="Don't run doctest")
parser.add_argument("-v",
                    action="count",
                    default=0,
                    dest="verbosity",
                    help="Increase verbosity")
parser.add_argument('tests', metavar='test', nargs='*')
parser.epilog = (
    'The database name can be specified in the DB_NAME '
    'environment variable.\n'
    "A database dump cache directory can be specified in the DB_CACHE "
    "environment variable. Dumps will be used to speed up re-run of tests.")
opt = parser.parse_args()

config.update_etc(opt.config)

if backend.name() == 'sqlite':
    database_name = ':memory:'
else:
    database_name = 'test_' + str(int(time.time()))
os.environ.setdefault('DB_NAME', database_name)

from trytond.tests.test_tryton import all_suite, modules_suite
if not opt.modules:
    suite = all_suite(opt.tests)
else:
    suite = modules_suite(opt.tests, doc=opt.doctest)
result = unittest.TextTestRunner(verbosity=opt.verbosity,
                                 failfast=opt.failfast).run(suite)
sys.exit(not result.wasSuccessful())
예제 #12
0
parser.add_argument("-c", "--config", dest="config",
    help="specify config file")
parser.add_argument("-f", "--failfast", action="store_true", dest="failfast",
    help="Stop the test run on the first error or failure")
parser.add_argument("-m", "--modules", action="store_true", dest="modules",
    default=False, help="Run also modules tests")
parser.add_argument("--no-doctest", action="store_false", dest="doctest",
    default=True, help="Don't run doctest")
parser.add_argument("-v", action="count", default=0, dest="verbosity",
    help="Increase verbosity")
parser.add_argument('tests', metavar='test', nargs='*')
parser.epilog = ('The database name can be specified in the DB_NAME '
    'environment variable.')
opt = parser.parse_args()

config.update_etc(opt.config)

if backend.name() == 'sqlite':
    database_name = ':memory:'
else:
    database_name = 'test_' + str(int(time.time()))
os.environ.setdefault('DB_NAME', database_name)

from trytond.tests.test_tryton import all_suite, modules_suite
if not opt.modules:
    suite = all_suite(opt.tests)
else:
    suite = modules_suite(opt.tests, doc=opt.doctest)
result = unittest.TextTestRunner(
    verbosity=opt.verbosity, failfast=opt.failfast).run(suite)
sys.exit(not result.wasSuccessful())
예제 #13
0
    def __init__(self, database_uri=None, user='******', language='en_US',
                 admin_password='',
                 super_pwd=None,
                 config_file=None):
        OrigConfigModule.Config.__init__(self)
        # FixMe: straighten this mess out

        if config_file is None:
            config_file = os.environ.get('TRYTOND_CONFIG')
        assert config_file and os.path.isfile(config_file), \
            "Set the environment variable TRYTOND_CONFIG to the path of TRYTOND CONFIG"

        if not database_uri:
            database_uri = os.environ.get('TRYTOND_DATABASE_URI')
        else:
            os.environ['TRYTOND_DATABASE_URI'] = database_uri
        assert os.path.isfile(config_file), \
            "set os.environ.get('TRYTOND_CONFIG') to be the Tryton config file"

        from trytond.config import config
        config.update_etc(config_file)

        from trytond.pool import Pool
        from trytond import backend
        from trytond.protocols.dispatcher import create
        from trytond.cache import Cache
        from trytond.transaction import Transaction
        self.database = database_uri
        database_name = None
        if database_uri:
            uri = urlparse.urlparse(database_uri)
            database_name = uri.path.strip('/')
        if not database_name:
            assert 'DB_NAME' in os.environ, \
                "Set os.environ['DB_NAME'] to be the database name"
            database_name = os.environ['DB_NAME']
        self.database_name = database_name
        self._user = user
        self.config_file = config_file

        Pool.start()
        if False:
           # new in 3.4
            self.pool = Pool(database_name)
            self.pool.init()
        else:
            # 3.2 code created the database if it did not exist
            with Transaction().start(None, 0) as transaction:
                cursor = transaction.cursor
                databases = backend.get('Database').list(cursor)
            if database_name not in databases:
                # trytond/protocols/dispatcher.py
                '''
                Create a database

                :param database_name: the database name
                :param password: the server password
                :param lang: the default language for the database
                :param admin_password: the admin password
                :return: True if succeed
                '''
                if not super_pwd:
                    sys.stderr.write(
                        "WARN: No super_pwd to create db %s\n" % (database_name,))
                    #! This is NOT the postgres server password
                    #! This calls security.check_super(password)
                    #! which is set in the conf file, [session]super_pwd
                    #! using crypt to generate it from from the command line
                    #! We default it to admin which may also be the
                    #! of the user 'admin': admin_password
                    super_pwd = 'admin'

                assert admin_password, "ERROR: No admin_password to create db " + database_name
                sys.stderr.write(
                    "create %s %s %s %s\n" % (database_name, super_pwd, language, admin_password,))
                create(database_name, super_pwd, language, admin_password)

            database_list = Pool.database_list()
            self.pool = Pool(database_name)
            if database_name not in database_list:
                self.pool.init()

        with Transaction().start(self.database_name, 0) as transaction:
            Cache.clean(database_name)
            User = self.pool.get('res.user')
            transaction.context = self.context
            self.user = User.search([
                ('login', '=', user),
                ], limit=1)[0].id
            with transaction.set_user(self.user):
                self._context = User.get_preferences(context_only=True)
            Cache.resets(database_name)
예제 #14
0
#unused files
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import os
import FSERP
import trytond
from trytond.config import config
# Load the configuration file
config.update_etc(
    os.path.join(os.getcwd(), 'FSERP', 'trytond', 'etc',
                 'trytond.conf'))  # Replace with your path
from trytond.pool import Pool
# from trytond.model import Cache
from trytond.cache import Cache
from trytond.transaction import Transaction

# dbname contains the db you want to use
dbname = 'testdb'
CONTEXT = {}

# Instantiate the pool
with Transaction().start(dbname, 1, context=CONTEXT):
    Pool.start()
    pool = Pool(dbname)

    # Clean the global cache for multi-instance
    Cache.clean(dbname)
    pool.init()

# User 0 is root user. We use it to get the admin id:
with Transaction().start(dbname, 1) as transaction:
예제 #15
0
from pyramid.config import Configurator

from .security.request import RequestWithUserAttribute
from .security import (Root, groupfinder)
from pyramid_beaker import session_factory_from_settings
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy

from trytond.transaction import Transaction
from trytond.pool import Pool

from trytond.config import config

config.update_etc('/ado/etc/trytond.conf')


def get_tryton_pool(request):
    Transaction().start('c3s', 0)
    pool = Pool()

    def _cleanup(request):
        Transaction().stop()

    request.add_finished_callback(_cleanup)
    return pool


def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    session_factory = session_factory_from_settings(settings)
예제 #16
0
from pyramid.config import Configurator

from .security.request import RequestWithUserAttribute
from .security import (
    Root,
    groupfinder
)
from pyramid_beaker import session_factory_from_settings
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy

from trytond.transaction import Transaction
from trytond.pool import Pool

from trytond.config import config
config.update_etc('/ado/etc/trytond.conf')


def get_tryton_pool(request):
    Transaction().start('c3s', 0)
    pool = Pool()

    def _cleanup(request):
        Transaction().stop()
    request.add_finished_callback(_cleanup)
    return pool


def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
예제 #17
0
파일: test_query.py 프로젝트: tinavas/FSERP
#unused files
import FSERP
import trytond
from trytond.config import config, parse_listen
import logging
import logging.config
import logging.handlers
#from trytond.ir.module import Module

config.update_etc('./FSERP/trytond/etc/trytond.conf')

from trytond.pool import Pool
from trytond.cache import Cache
from trytond.transaction import Transaction
result = None

if __name__ == '__main__':
    logformat = '[%(asctime)s] %(levelname)s:%(name)s:%(message)s'
    datefmt = '%a %b %d %H:%M:%S %Y'
    logging.basicConfig(level=logging.INFO, format=logformat, datefmt=datefmt)

    logger = logging.getLogger(__name__)

    context = {}
    dbname = 'testdb'
    Pool.start()
    pool = Pool(dbname)

    #Cache.clean(dbname)

    # Instantiate the pool
예제 #18
0
 def __call__(self, environ, start_response):
     if not self.loaded:
         config.update_etc(environ.get('trytond.config'))
         self.loaded = True
     return app.wsgi_app(environ, start_response)
예제 #19
0
# Tryton related imports
import FSERP
import trytond
from trytond.config import config, parse_listen
from proteus import config as con

import config_fserp

conf = con.set_trytond('testdbkitchen',
                       user='******',
                       config_file=os.path.join(os.getcwd(), 'FSERP',
                                                'trytond', 'etc',
                                                'trytond.conf'))

config.update_etc(config_fserp.TRYTON_CONFIG_FILE)

# local module imports
from GUI.notification import Notification
from admin.authandadmin import Login, Admin  ##call this to check the authenticity of the user
from GUI.gui import Gui


class MainWindow():
    """
       The main application
    """
    def __init__(self):
        logger.info("inside constructor...")
        self.login = Login()
        self.login.exec_()