def stream_via_token(cls, token): ''' Set token user to online and publish presence of this user to all friends. ''' NereidUser = Pool().get('nereid.user') if hasattr(current_app, 'redis_client'): redis_client = current_app.redis_client else: redis_client = Redis( CONFIG.get('redis_host', 'localhost'), int(CONFIG.get('redis_port', 6379)) ) key = 'chat:token:%s' % token if not redis_client.exists(key): abort(404) nereid_user = NereidUser(int(redis_client.get(key))) nereid_user.broadcast_presence() return Response( cls.generate_event_stream( nereid_user.id, Transaction().cursor.dbname ), mimetype='text/event-stream' )
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 _get_es_connection(): """ Return a PYES connection """ return ES( CONFIG.get('elastic_search_server', 'localhost:9200').split(',') )
def token(cls): ''' Generate token for current_user with TTL of 1 hr. ''' if hasattr(current_app, 'redis_client'): redis_client = current_app.redis_client else: redis_client = Redis(CONFIG.get('redis_host', 'localhost'), int(CONFIG.get('redis_port', 6379))) token = unicode(uuid.uuid4()) key = 'chat:token:%s' % token # Save token to redis and set TTL of 1 hr. redis_client.set(key, current_user.id) redis_client.expire(key, 3600) return jsonify({'token': token})
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 test(dbtype, name, modules, failfast, upload=True): if older_version: CONFIG['db_type'] = dbtype if not CONFIG['admin_passwd']: CONFIG['admin_passwd'] = 'admin' elif dbtype != 'sqlite': CONFIG.set('database', 'uri', 'postgresql:///') if dbtype == 'sqlite': database_name = ':memory:' else: database_name = 'test_' + str(int(time.time())) if name is None: name = '' os.environ['DB_NAME'] = database_name cov = coverage() cov.start() from trytond.tests.test_tryton import modules_suite import proteus.tests suite = None if modules: suite = modules_suite(modules) else: suite = modules_suite() suite.addTests(proteus.tests.test_suite()) runner = TrytonTestRunner.TrytonTestRunner(failfast=failfast, coverage=cov) runner.run(suite) if modules: name = name + " [" + ','.join(modules) + "]" logger.info('Upload results to tryton') if upload: print(("Uploading to Tryton '%s'" % name)) runner.upload_tryton(dbtype, failfast, name) print(("'%s' uploaded." % name)) else: runner.print_report(dbtype, failfast, 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) 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()
def token(cls): ''' Generate token for current_user with TTL of 1 hr. ''' if hasattr(current_app, 'redis_client'): redis_client = current_app.redis_client else: redis_client = Redis( CONFIG.get('redis_host', 'localhost'), int(CONFIG.get('redis_port', 6379)) ) token = unicode(uuid.uuid4()) key = 'chat:token:%s' % token # Save token to redis and set TTL of 1 hr. redis_client.set(key, current_user.id) redis_client.expire(key, 3600) return jsonify({ 'token': token })
def stream_via_token(cls, token): ''' Set token user to online and publish presence of this user to all friends. ''' NereidUser = Pool().get('nereid.user') if hasattr(current_app, 'redis_client'): redis_client = current_app.redis_client else: redis_client = Redis(CONFIG.get('redis_host', 'localhost'), int(CONFIG.get('redis_port', 6379))) key = 'chat:token:%s' % token if not redis_client.exists(key): abort(404) nereid_user = NereidUser(int(redis_client.get(key))) nereid_user.broadcast_presence() return Response(cls.generate_event_stream(nereid_user.id, Transaction().cursor.dbname), mimetype='text/event-stream')
def start_servers(self): # Launch Server for proto, _class in protocols.PROTOCOLS.iteritems(): if proto not in CONFIG.options or not CONFIG[proto]: continue ssl_config = CONFIG.get('ssl_%s' % proto, False) for hostname, port in CONFIG[proto]: self.servers[proto].append(_class(hostname, port, ssl_config)) self.logger.info("starting %s%s protocol on %s:%d" % (proto.upper(), ssl_config and ' SSL' or '', hostname or '*', port)) for proto, servers in self.servers.iteritems(): for server in servers: server.start()
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()
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()
if __name__ == '__main__': from optparse import OptionParser usage = "usage: %prog [options] database filename" parser = OptionParser(usage=usage) parser.add_option('-c', '--config', dest="config", default=None, help="The tryton configuration file to use") (options, args) = parser.parse_args() if len(args) != 2: parser.error("Expected 2 argument got %d" % len(args)) if options.config is not None: from trytond.config import CONFIG CONFIG.configfile = options.config CONFIG.load() # Register the classes and get all the modules from the pool from trytond.modules import register_classes register_classes() from trytond.pool import Pool pool = Pool(args[0]) pool.init() with open(args[1], 'wb') as file: base_source = BaseSource.from_tryton_config(args[0]) file.write(base_source.as_string()) for model_object in iter_sql_models(pool): ds = DataSource.from_model(model_object, base_source)
def default_servers(): """ Find the server from config and return """ return CONFIG.get('elastic_search_server', 'localhost:9200')
"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()))
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:
#!/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')
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(),
from trytond.pool import PoolMeta, Pool from trytond.modules.nereid.party import AddressForm from trytond.config import CONFIG from nereid import request, current_app __metaclass__ = PoolMeta __all__ = ['Address'] geoip = None try: from pygeoip import GeoIP except ImportError: logging.error("pygeoip is not installed") else: path = os.environ.get('GEOIP_DATA_PATH', CONFIG.get('geoip_data_path')) if path: geoip = GeoIP(path) class WebshopAddressForm(AddressForm): """Custom address form for webshop """ def get_default_country(self): """Get the default country based on geoip data. """ if not geoip: return None Country = Pool().get('country.country') try: