def adduser(dbname, user, conf_file=None): '''Create new user or reset the password if the user exist''' if not conf_file: conf_file = 'server-%s.cfg' % (socket.gethostname()) if not os.path.isfile(conf_file): print t.red("File '%s' not found" % (conf_file)) return CONFIG.update_etc(conf_file) Pool.start() pool = Pool(dbname) pool.init() with Transaction().start(dbname, 1, context={'active_test': False}): User = pool.get('res.user') users = User.search([ ('login', '=', user), ], limit=1) if users: u, = users else: admin, = User.search([ ('login', '=', 'admin'), ], limit=1) u, = User.copy([admin]) u.name = user u.login = user u.password = getpass.getpass() u.save() Transaction().commit() print t.green("You could login with '%s' at '%s'" % (u.login, dbname))
def __init__(self, options): format = '[%(asctime)s] %(levelname)s:%(name)s:%(message)s' datefmt = '%a %b %d %H:%M:%S %Y' logging.basicConfig(level=logging.INFO, format=format, datefmt=datefmt) CONFIG.update_etc(options['configfile']) CONFIG.update_cmdline(options) if CONFIG['logfile']: logf = CONFIG['logfile'] # test if the directories exist, else create them try: diff = 0 if os.path.isfile(logf): diff = int(time.time()) - int(os.stat(logf)[-1]) handler = logging.handlers.TimedRotatingFileHandler( logf, 'D', 1, 30) handler.rolloverAt -= diff except Exception, exception: sys.stderr.write(\ "ERROR: couldn't create the logfile directory:" \ + str(exception)) else: formatter = logging.Formatter(format, datefmt) # tell the handler to use this format handler.setFormatter(formatter) # add the handler to the root logger logging.getLogger().addHandler(handler) logging.getLogger().setLevel(logging.INFO)
def set_context(database_name, config_file=os.environ.get('TRYTOND_CONFIG')): CONFIG.update_etc(config_file) if not Transaction().connection: return Transaction().start(database_name, 0) else: return contextlib.nested(Transaction().new_transaction(), Transaction().set_user(0), Transaction().reset_context())
def run(config, host, port, debug, threaded): """ Runs the application on a local development server. """ if config: CONFIG.update_etc(config) if hasattr(CONFIG, 'set_timezone'): CONFIG.set_timezone() from application import app app.run(host, port, debug=debug, threaded=threaded)
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: from trytond.config import CONFIG CONFIG.update_etc(self.tryton_configfile) from trytond.backend import Database from trytond.modules import register_classes register_classes() from trytond.pool import Pool # Load and initialise pool self._database = Database(self.database_name).connect() self._pool = Pool(self.database_name) self._pool.init()
def __init__(self, database_name=None, user='******', database_type=None, language='en_US', password='', config_file=None): super(TrytondConfig, self).__init__() from trytond.config import CONFIG CONFIG.update_etc(config_file) CONFIG.set_timezone() if database_type is not None: CONFIG['db_type'] = database_type 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_type = CONFIG['db_type'] if database_name is None: if self.database_type == 'sqlite': database_name = ':memory:' else: database_name = 'test_%s' % int(time.time()) self.database_name = database_name self._user = user self.config_file = config_file Pool.start() with Transaction().start(None, 0) as transaction: cursor = transaction.cursor databases = backend.get('Database').list(cursor) if database_name not in databases: create(database_name, CONFIG['admin_passwd'], language, 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)
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) register_classes() # Load and initialise pool Database = backend.get('Database') self._database = Database(self.database_name).connect() self._pool = Pool(self.database_name) self._pool.init()
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) CONFIG.set_timezone() register_classes() # Load and initialise pool Database = backend.get('Database') self._database = Database(self.database_name).connect() self._pool = Pool(self.database_name) self._pool.init()
for product_ice_id in set(product_ice_ids) - set(existing_product_ice_ids): create_product.delay(product_ice_id, company) del data if __name__ == '__main__': usage = "Usage: %prog [options] database" parser = OptionParser(usage=usage) parser.add_option("-c", "--config", dest="config", default=None) parser.add_option("-f", "--file", dest="filename", default=None) (options, args) = parser.parse_args() DATABASE = args[0] if options.config: from trytond.config import CONFIG CONFIG.update_etc(options.config) from trytond.modules import register_classes register_classes() from trytond.pool import Pool pool = Pool(DATABASE) pool.init() from trytond.transaction import Transaction with Transaction().start(DATABASE, 1, None) as txn: create_products_from_xml(options.filename) txn.cursor.commit()
"Error on URI creation for Category ID:%s\n%s" % (cat_id, exc) ) else: raise exc logging.info("URI creation completed") if __name__ == '__main__': usage="Usage: %prog [options] database category_file" parser = OptionParser(usage=usage) parser.add_option("-c", "--config", dest="config", default=None) (options, args) = parser.parse_args() DATABASE, FILE = args if options.config: from trytond.config import CONFIG CONFIG.update_etc(options.config) from trytond.modules import register_classes register_classes() from trytond.pool import Pool pool = Pool(DATABASE) pool.init() from trytond.transaction import Transaction with Transaction().start(DATABASE, 1, None) as txn: create_categories_from_file(FILE) txn.cursor.commit()
parser.add_option("-c", "--config", dest="config", help="specify config file") parser.add_option("-m", "--modules", action="store_true", dest="modules", default=False, help="Run also modules tests") opt, args = parser.parse_args() if args: parser.error("Invalid argument") if opt.modules: _MODULES = True if opt.config: _CONFIGFILE = opt.config from trytond.config import CONFIG CONFIG['db_type'] = 'sqlite' CONFIG.update_etc(_CONFIGFILE) if not CONFIG['admin_passwd']: CONFIG['admin_passwd'] = 'admin' from trytond.pool import Pool from trytond.backend import Database from trytond.protocols.dispatcher import create from trytond.transaction import Transaction from trytond.pyson import PYSONEncoder, Eval Pool.start() if CONFIG['db_type'] == 'sqlite': DB_NAME = ':memory:' else: DB_NAME = 'test_' + str(int(time.time()))
import os import datetime import mimetypes from nereid import Nereid from werkzeug.contrib.sessions import FilesystemSessionStore from nereid.contrib.locale import Babel from nereid.sessions import Session from raven.contrib.flask import Sentry CWD = os.path.abspath(os.path.dirname(__file__)) DATABASE_NAME = os.environ.get('TRYTOND_DB_NAME', 'nereid_project') SECRET_PATH = os.environ.get('SECRET_PATH', '.secret') from trytond.config import CONFIG CONFIG.update_etc() APP_CONFIG = dict( # The name of database DATABASE_NAME=DATABASE_NAME, # If the application is to be configured in the debug mode DEBUG=False, # The location where the translations of this template are stored TRANSLATIONS_PATH='i18n', SECRET_KEY=open(SECRET_PATH).read(),
#!/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')
from BaseHTTPServer import BaseHTTPRequestHandler, DEFAULT_ERROR_MESSAGE #: This parameter specifies the origin URLs from which the tryton server can #: accept requests. While specifying '*' here might seem like a security hole #: this is usually how your trytond runs anyway! listening to requests from #: all IPs ALLOW_ORIGIN = "*" #: These are the only headers that are required by the app ALLOW_HEADERS = "origin, x-requested-with, content-type" #: If you have your config file in an unconventional location CONFIG_PATH = 'trytond.conf' from trytond.config import CONFIG CONFIG.update_etc(CONFIG_PATH) from trytond.protocols.jsonrpc import object_hook, JSONEncoder from trytond.protocols.dispatcher import dispatch from trytond.pool import Pool from trytond.exceptions import UserError, UserWarning, NotLogged, \ ConcurrencyException Pool.start() def jsonrpc_app(environ, start_response): 'JSON-RPC dispatcher' if environ['REQUEST_METHOD'] == 'POST': body = '' try: length = int(environ.get('CONTENT_LENGTH', '0')) except ValueError:
from nereid import Nereid from trytond.config import CONFIG CONFIG.update_etc('/home/umangarora/trytond.conf') app = Nereid() app.config.update({ 'DATABASE_NAME': 'tul2014', 'SECRET_KEY': 'somekey', }) app.initialise() if __name__ == '__main__': app.debug = True app.run()