def main(): """The main command loader. Args: module_name (str): The main module name (where `app.init()` lives). """ if pyfiglet: figlet = pyfiglet.Figlet(font='slant') text = figlet.renderText(conf.get('PROJECT_NAME')) else: text = conf.get('PROJECT_NAME', 'frf') + '\n' col = colors.ColorText() sys.stdout.writelines([col.lightmagenta(text).value(), '~' * 70, '\n']) argv = sys.argv[:] args, _ = globalparser.parse_known_args() commands = find_commands() if args.command: if args.command not in commands: sys.stderr.writelines( ['Command not found: {}\n\n'.format(args.command), '\n']) sys.exit(-1) argv = argv[2:] # create a new parser parser = CommandArgumentParser(args.command, description='Run management commands.') command = commands[args.command]() command.add_arguments(parser) if getattr(command, 'parse_arguments', True): args = parser.parse_args(argv) command.handle(args) else: sys.stdout.writelines([ 'usage: manage.py [command] [options]...\n\n', 'The following commands are available:\n\n', ]) table = [] keys = list(commands.keys()) keys.sort() for command in keys: cls = commands.get(command) table.append((col.reset(' ').green(command).reset('').value(), col.reset('- ').reset( getattr(cls, 'description', 'no description provided')).value())) sys.stdout.writelines( [tabulate.tabulate(table, tablefmt='plain'), '\n'])
def now(): """Return a timezone aware version of `now`. Converts the time to the timezone mentioned in the ``TIMEZONE`` setting, or ``UTC`` if the ``TIMEZONE`` setting is not provided. """ dt = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) if conf.get('TIMEZONE'): dt = dt.astimezone(pytz.timezone(conf.get('TIMEZONE'))) return dt
def truncate_all(): """Truncate all tables. Useful for the testing databases. """ if not engine or not session: raise DatabaseError('Database is not yet initialized') session.close() with contextlib.closing(engine.connect()) as con: trans = con.begin() for app_name in conf.get('INSTALLED_APPS', []): try: module = importlib.import_module('{}.models'.format(app_name)) for attr_name in dir(module): attr = getattr(module, attr_name) if inspect.isclass(attr) and issubclass( attr, models.Model): # truncate the table con.execute(attr.__table__.delete()) except ImportError: pass trans.commit()
def find_commands(): """Load command modules. Loads the default command modules, plus the modules from the `COMMAND_MODULES` setting. """ module_names = [ 'frf.commands.runserver', 'frf.commands.shell', 'frf.commands.test', 'frf.commands.syncdb', 'frf.commands.startapp', ] module_names += conf.get('COMMAND_MODULES', []) commands = {} for module_name in module_names: module = importlib.import_module(module_name) cls = getattr(module, 'Command', None) if not cls: sys.stderr.write('Could not get management command' ' from class: {}.Command\n'.format(module_name)) sys.exit(-1) command_name = module_name[module_name.rfind('.') + 1:] commands[command_name] = cls return commands
def setUp(self): self.sqlalchemy_test_uri = conf.get('SQLALCHEMY_TEST_CONNECTION_URI') if self.sqlalchemy_test_uri: # set up the test database tables db.create_all() super().setUp()
def error_serializer(req, resp, exception): body = exception.to_dict() if conf.get('DEBUG', False): body['traceback'] = traceback.format_exc() headers = getattr(exception, 'headers') if headers: resp.set_headers(headers) resp.body = json.dumps(body)
def setup_database(self): sqlalchemy_test_uri = conf.get('SQLALCHEMY_TEST_CONNECTION_URI') if conf.get('SQLALCHEMY_CONNECTION_URI') \ and not sqlalchemy_test_uri: self.error( 'You must set `SQLALCHEMY_TEST_CONNECTION_URI` in your ' 'settings file.') sys.exit(-1) if sqlalchemy_test_uri: self.info('Setting up testing database ... ', end='') db.init(sqlalchemy_test_uri) self.info('Done.') self.info('Creating tables ... ', end='') db.drop_all() db.create_all() self.info('Done.')
def handle(self, args): self.greet('Oh hai, starting gunicorn...') app_name = os.path.basename(conf.get('BASE_DIR')) os.system( 'gunicorn {} --access-logfile - --error-logfile - --bind {} ' '--workers {} --timeout {} --threads {} {}:app.api'.format( '--reload' if args.reload == 'reload' else '', args.bind, args.workers, args.timeout, args.threads, app_name, ))
def create_all(): """Create all tables in the database. Tables that already exist in the database will not be changed. """ if not engine or not session: raise DatabaseError('Database is not yet initialized') # make sure all models are imported for app_name in conf.get('INSTALLED_APPS', []): try: importlib.import_module('{}.models'.format(app_name)) except ImportError: pass models.Model.metadata.create_all(engine)
def drop_all(): """Drop all tables from the database. An error will NOT be thrown if a table does not exist in the database. """ if not engine or not session: raise DatabaseError('Database is not yet initialized') session.close() for app_name in conf.get('INSTALLED_APPS', []): try: importlib.import_module('{}.models'.format(app_name)) except ImportError: pass models.Model.metadata.drop_all(engine)
def handle(self, args): models = [] for app_name in conf.get('INSTALLED_APPS', []): models_module = importlib.import_module( '{}.models'.format(app_name)) for attr_name in dir(models_module): attr = getattr(models_module, attr_name) if inspect.isclass(attr) and issubclass( attr, falconmodels.Model): models.append(attr) if not models: self.error('No models were found. Have you added your app ' 'to "INSTALLED_APPS"?') else: self.info('Creating tables...', end='') falconmodels.Model.metadata.create_all(db.engine) self.info(' Done.')
def test_timezone_now(self): n = timezone.now() self.assertEquals( str(n.tzinfo), str(pytz.timezone(conf.get('TIMEZONE'))))