def ping(self): """Ping our application to not allow heroku idle it """ if config.Application().heroku_url is None: return heroku_url = config.Application().heroku_url log.msg('Heroku Awakening: Pinging {}'.format(heroku_url)) return Agent(reactor).request( 'GET', '{url}/_mamba_pong'.format(url=str(heroku_url)), Headers({'User-Agent': ['Mamba Heroku Web Client']}), None)
def register_route(self, controller, route, func_name): """Method that register a route for the given controller :param controller: the controller where to register the route :type controller: :class:`~mamba.Controller` :param route: the :class:`~mamba.Route` to register :type route: :class:`~mamba.web.Route` :param func_name: the callable object name :type func_name: str """ controller_name = controller.__class__.__name__ if getattr(config.Application(), 'debug', False): bold = output.bold log.msg( bold('Registering route:') + ' {route}'.format(route=route)) try: if type(route.method) in [tuple, list]: for method in route.method: self.routes[method][route.url][controller_name] = route else: self.routes[route.method][route.url][controller_name] = route except KeyError as error: raise RouterError( '{} is not a valid request method, at action {} in controller ' '{}, valid mathods are: GET, POST, PUT, DELETE, OPTIONS, ' 'PATCH and HEAD. Cant register route {}'.format( error.message, func_name, controller_name, route.url))
def test_pack_fails_on_no_README_or_no_LICENSE(self): with fake_project(): self.config.parseOptions() self.assertRaises(usage.UsageError, self.packer.pack_application, 'sdist', self.config, config.Application('config/application.json'))
def test_pack_fails_on_no_docs_directory(self): with self._generate_README_and_LICENSE(): self.config.parseOptions() self.assertRaises(usage.UsageError, self.packer.pack_application, 'sdist', self.config, config.Application('config/application.json')) self.assertTrue(os.path.exists('README.rst')) self.assertTrue(os.path.exists('LICENSE')) self.assertFalse(os.path.exists('docs'))
def handle_start_command(options): """I handle the start command """ if GNU_LINUX or BSD: app = config.Application('config/application.json') if app.port <= 1024: if os.getuid() != 0: print( '[{e}]: This application is configured to use a reserved ' 'port (a port under 1025) only root can open a port from ' 'this range root access is needed to start this ' 'application using the {port} port.\n\nTry something ' 'like: sudo mamba-admin start\n\nYou can also change the ' 'configuration for this application editing ' '\'config/application.json\''.format( e=darkred('ERROR'), port=app.port ) ) sys.exit(-1) args = ['twistd'] try: app_name = glob.glob( 'twisted/plugins/*.py')[0].split(os.sep)[-1].split('_')[0] except IndexError: print( 'error: twisted directory can\'t be found. You should be in ' 'the application directory in order to start it' ) sys.exit(-1) if filepath.exists('twistd.pid'): print( 'error: twistd.pid found, seems like the application is ' 'running already. If the application is not running, please ' 'delete twistd.pid and try again' ) sys.exit(-1) if BSD: args.append('--reactor=kqueue') args.append(app_name) if options.subOptions.opts['port']: args.append('--port={}'.format(options.subOptions.opts['port'])) print('starting application {}...'.format(app_name).ljust(73), end='') if subprocess.call(args) == 0: print('[{}]'.format(darkgreen('Ok'))) sys.exit(0) else: print('[{}]'.format(darkred('Fail'))) sys.exit(-1)
def test_application_load(self): config.Application('../mamba/test/dummy_app/config/application.json') self.assertTrue(config.Application().loaded) self.assertEqual(config.Application().name, 'dummy') self.assertEqual( config.Application().description, 'This is a Dummy application just for testing purposes') self.assertEqual(config.Application().version, '0.1.2') self.assertEqual(config.Application().port, 8080) self.assertEqual(config.Application().logfile, None)
def test_pack_sdist(self): result = yield utils.getProcessValue('mamba-admin', [], os.environ) if result == 1: raise unittest.SkipTest('mamba framework is not installed yet') with self._generate_docs(): self.config.parseOptions() self.config['name'] = 'mamba-dummy' self.packer.pack_application( 'sdist', self.config, config.Application('config/application.json')) self.assertTrue(os.path.exists('mamba-dummy-0.1.2.tar.gz')) self.packer.do(['rm', 'mamba-dummy-0.1.2.tar.gz'])
def register_route(self, controller, route): """ Decorator that register a route for the given controller :param controller: the controller where to register the route :type controller: :class:`~mamba.Controller` :param route: the :class:`~mamba.Route` to register :type route: :class:`~mamba.web.Route` """ controller_name = controller.__class__.__name__ if getattr(config.Application(), 'debug', False): bold = output.bold log.msg( bold('Registering route:') + ' {route}'.format(route=route)) self.routes[route.method][route.url][controller_name] = route
def test_pack_egg(self): result = yield utils.getProcessValue('mamba-admin', [], os.environ) if result == 1: raise unittest.SkipTest('mamba framework is not installed yet') with self._generate_docs(): self.config.parseOptions() self.config['name'] = 'mamba-dummy' self.packer.pack_application( 'bdist_egg', self.config, config.Application('config/application.json')) major, minor = sys.version_info[:2] self.assertTrue( os.path.exists('mamba_dummy-0.1.2-py{}.{}.egg'.format( major, minor))) self.packer.do( ['rm', 'mamba_dummy-0.1.2-py{}.{}.egg'.format(major, minor)])
from zope.interface import implements from twisted.python import usage from twisted.plugin import IPlugin from twisted.application.service import IServiceMaker from twisted.application import internet from mamba.utils import config from dummy import MambaApplicationFactory settings = config.Application('config/application.json') class Options(usage.Options): optParameters = [[ 'port', 'p', settings.port, 'The port number to listen on' ]] class MambaServiceMaker(object): implements(IServiceMaker, IPlugin) tapname = settings.name description = settings.description options = Options def makeService(self, options): """Construct a TCPServer from a factory defined in pericote """ factory, application = MambaApplicationFactory(settings) httpserver = internet.TCPServer(int(options['port']), factory) httpserver.setName('{} Application'.format(settings.name))
def dump(self, model_manager, full=False): """ Dumps the full database :param model_manager: the model manager from mamba application :type model_manager: :class:`~mamba.application.model.ModelManager` :param full: should be dumped full? :type full: bool """ references = [] indexes = [] sql = [ '--', '-- Mamba SQL dump {}'.format(version.short()), '--', '-- Database Backend: {}'.format(self.backend), '-- Host: {}\tDatabase: {}'.format(self.host, self.database) ] app = config.Application('config/application.json') try: sql += [ '-- Application: {}'.format(app.name.decode('utf-8')), '-- Application Version: {}'.format(app.version), '-- Application Description: {}'.format( app.description.encode('utf-8') ) ] except AttributeError: pass sql += [ '-- ---------------------------------------------------------', '-- Dumped on: {}'.format(datetime.datetime.now().isoformat()), '--' ] if self.backend == 'mysql': sql += [ '-- Disable foreign key checks for table creation', '--', 'SET FOREIGN_KEY_CHECKS = 0;' ] if full is False: sql.append('') for model in model_manager.get_models().values(): if not model.get('object').on_schema(): continue if self.backend == 'postgres': references.append(model.get('object').dump_references()) if self.backend in ('postgres', 'sqlite'): if model.get('object').dump_indexes(): indexes.append(model.get('object').dump_indexes()) sql += [model.get('object').dump_table() + '\n'] else: for model in model_manager.get_models().values(): model_object = model.get('object') if not model_object.on_schema(): continue sql.append('--') sql.append('-- Table structure for table {}'.format( model_object.__storm_table__ )) sql.append('--\n') sql.append(model_object.dump_table()) sql.append('--') sql.append('-- Dumping data for table {}'.format( model_object.__storm_table__ )) sql.append('--\n') sql.append(model_object.dump_data()) if self.backend == 'postgres': references.append(model_object.dump_references()) if self.backend in ('postgres', 'sqlite'): if model.get('object').dump_indexes(): indexes.append(model_object.dump_indexes()) if self.backend == 'mysql': sql += [ '--', '-- Enable foreign key checks', '--', 'SET FOREIGN_KEY_CHECKS = 1;' ] for reference in references: sql.append(reference) for index in indexes: sql.append(index) return '\n'.join(sql)
def tearDown(self): config.Application('default')
def test_fallback_works(self): self.assertFalse(config.Application().loaded) self.assertEqual(config.Application().name, None) self.assertEqual(config.Application().port, None) self.assertEqual(config.Application().description, None) self.assertEqual(config.Application().doctype, 'html')
def __init__(self): self.name = 'HerokuService' self.on_heroku = heroku.are_we_on_heroku() self.allowed = config.Application().force_heroku_awake self.ping_task = task.LoopingCall(self.ping)
def dump(self, model_manager, scheme=None, full=False): """ Dumps the full database :param model_manager: the model manager from mamba application :type model_manager: :class:`~mamba.application.model.ModelManager` :param scheme: dump which scheme? if None just everything :type scheme: str :param full: should be dumped full? :type full: bool """ references = [] indexes = [] backend, host, database = self._parse_config_scheme(scheme) sql = [ '--', '-- Mamba SQL dump {}'.format(version.short()), '--', '-- Database Backend: {}'.format(backend), '-- Host: {}\tDatabase: {}'.format(host, database) ] app = config.Application('config/application.json') try: sql += [ '-- Application: {}'.format(app.name.decode('utf-8')), '-- Application Version: {}'.format(app.version), '-- Application Description: {}'.format( app.description.encode('utf-8') ) ] except AttributeError: pass sql += [ '-- ---------------------------------------------------------', '-- Dumped on: {}'.format(datetime.datetime.now().isoformat()), '--' ] if self.backend == 'mysql': sql += [ '-- Disable foreign key checks for table creation', '--', 'SET FOREIGN_KEY_CHECKS = 0;' ] if full is False: self._dump_scheme(sql, references, indexes, model_manager, scheme) else: self._dump_data(sql, references, indexes, model_manager, scheme) if self.backend == 'mysql': sql += [ '--', '-- Enable foreign key checks', '--', 'SET FOREIGN_KEY_CHECKS = 1;' ] for reference in references: sql.append(reference) for index in indexes: sql.append(index) return '\n'.join(sql)