def quickstart(): "Richtet DB und FTP ein" if prompt_bool("Datenbank einrichten?"): populate() if not prompt_bool("FTP einrichten?"): return structure = { "Users": {}, "Libraries": {l.name: {} for l in Lang.query}, "Games": {str(g.id): { l.name: {"example_ai": {}, "ailib": {}} for l in Lang.query } for g in GameType.query}, "Data": {}, "AIs": {}, "Tournaments": {} } @ftp.safe def ftp_safe(): def f(k, v, path=""): p = path + k if not ftp.ftp_host.path.isdir(p): print("MKDIR:", p) ftp.ftp_host.mkdir(p) else: print("EXISTS:", p) for k, v in v.items(): f(k, v, p + "/") for k, v in structure.items(): f(k, v) print("Vergess nicht das Standartbild in AIs/default.png zu setzen.") try: ftp_safe() except ftp.err: print("FTP-Zeugs hat nicht geklappt!")
def clean_db(): "Löscht die DB, und füllt sie mit Beispieldaten." if prompt_bool("Sicher, die DB zu leeren?"): with app.app_context(): db.drop_all() if prompt_bool("Mit Daten füllen"): populate()
def useradd(email=None, level=None): """add an api user""" import api_user from adsabs.modules.user import AdsUser if not email: email = prompt("Enter e-mail address of Classic ADS account", "") if not len(email): sys.exit(1) if not level: level = prompt_choices("Enter developer permission level", sorted(api_user.PERMISSION_LEVELS.keys()), "basic") if level not in api_user.PERMISSION_LEVELS: sys.exit(1) user = AdsUser.from_email(email) if not user: app.logger.info("user not found") sys.exit(1) # first check if the user is already a dev user = api_user.AdsApiUser(user.user_rec) if user.is_developer(): app.logger.info("User already has api access. Developer key: %s" % user.get_dev_key()) if prompt_bool("Would you like to reset the user's permissions", False): user.set_perms(level) app.logger.info("API User permissions updated") return user = api_user.create_api_user(user, level) dev_key = user.get_dev_key() app.logger.info("API User created with %s permissions. Developer key: %s" % (level, dev_key)) if prompt_bool("Send welcome message", True): sendwelcome(dev_key=dev_key, no_prompt=True)
def initflaskbb(username=None, password=None, email=None): """Initializes FlaskBB with all necessary data""" app.logger.info("Creating default groups...") try: create_default_groups() except IntegrityError: app.logger.error("Couldn't create the default groups because they are\ already exist!") if prompt_bool("Do you want to recreate the database? (y/n)"): db.session.rollback() db.drop_all() db.create_all() create_default_groups() else: sys.exit(0) except OperationalError: app.logger.error("No database found.") if prompt_bool("Do you want to create the database? (y/n)"): db.session.rollback() db.create_all() create_default_groups() else: sys.exit(0) app.logger.info("Creating admin user...") if username and password and email: create_admin_user(username=username, password=password, email=email) else: create_admin() app.logger.info("Creating welcome forum...") create_welcome_forum() app.logger.info("Congratulations! FlaskBB has been successfully installed")
def drop(db_name): "Drops database tables" if db_name == 'small': if prompt_bool("Are you sure you want to lose all your data"): db.drop_all(bind=None) elif db_name == 'large': if prompt_bool("Are you sure you want to lose all your data"): db.drop_all(bind='large_db') else: print "No DB named {}.".format(db_name) print "Done"
def recompile_ais(): "Kompiliert KIs" if prompt_bool("Quali KIs rekompilieren"): for gt in GameType.query.all(): _compile_quali_ai(gt) all = prompt_bool("Compile all?") for ai in AI.query.all(): if all or prompt_bool("Compile '"+ai.name + "' by " + ai.user.name): ai.latest_version().compiled = True print("Compiling", ai.name) for data, event in backend.compile(ai): print(event, ":", data) db.session.commit()
def recompile_ais(): "Kompiliert KIs" if prompt_bool("Quali KIs rekompilieren"): for gt in GameType.query.all(): _compile_quali_ai(gt) all = prompt_bool("Compile all?") for ai in AI.query.all(): if all or prompt_bool("Compile '" + ai.name + "' by " + ai.user.name): ai.latest_version().compiled = True print("Compiling", ai.name) for data, event in backend.compile(ai): print(event, ":", data) db.session.commit()
def setup(): """ Populate the database with some defaults """ if prompt_bool("Do you want to add an admin user?"): name = prompt("Username for admin") password = prompt("Password for admin") user = User(name=name, password=password, role='admin') db.session.add(user) db.session.commit() if prompt_bool("Create a guest user?"): name = prompt("Username for guest") password = prompt("Password for guest") user = User(name=name, password=password, role='guest') db.session.add(user) db.session.commit()
def run(self): if prompt_bool("Are you sure you want to lose all your data"): app.app.configure( SQLALCHEMY_ECHO=True, ) from nyapics.models import db db.drop_all()
def init_db(no_confirm=False, drop_all_tables=False): '''This will create the database from scratch''' # Unless the no_confirm parameter is true, prompt user for a response, converted to a boolean. # If the response is negative (false), cancel the operation and return. Otherwise, keeep going. if not no_confirm: try: if not prompt_bool("This will DESTROY all data in database and download new data. Are you sure"): print "Cancelled" return except EOFError: print "\nInvalid response. Aborting." return if drop_all_tables: drop_tables = db.engine.table_names() else: drop_tables = [sales_data.table] print "Dropping tables: %s" % drop_tables for table in drop_tables: try: db.engine.execute("DROP TABLE %s" % table) except SQLAlchemyError as e: print "Table %s does not exist\n%s" % (table, e)
def init_db(no_confirm=False, drop_all_tables=False): '''Create the database from scratch. This will DELETE any data already in the database. no_confirm will skip user confirmation drop_all_tables will reset the entire database, not just the table set in the app's config ''' # Unless the no_confirm parameter is true, prompt user for a response, converted to a boolean. # If the response is negative (false), cancel the operation and return. Otherwise, keeep going. if not no_confirm: try: if not prompt_bool( "This will DESTROY all data in database and download new data. Are you sure"): print "Cancelled" return except EOFError: print "\nInvalid response. Aborting." return if drop_all_tables: drop_tables = db.engine.table_names() else: drop_tables = [sales_data.table] print "Dropping tables: %s" % drop_tables for table in drop_tables: try: db.engine.execute("DROP TABLE %s" % table) except SQLAlchemyError: # Raised if table doesn't exist print "(table %s does not exist)" % table print "\nInitializing database..." sales_data.create_from_scratch()
def initialize(): """ initialize system(data) """ if prompt_bool( u"Warning: the initialization system will drop all data! Are you sure?" ): db.drop_all() db.create_all() ds.create_role(name='restricter', description='受限的') ds.create_role(name='member', description='普通会员') ds.create_role(name='enthusiast', description='热心会员') ds.create_role(name='mainstay', description='支柱会员') ds.create_role(name='senior', description='资深会员') ds.create_role(name='partner', description='合作伙伴') ds.create_role(name='editor', description='编辑') ds.create_role(name='moderator', description='版主、仲裁者') ds.create_role(name='supervisor', description='管理员') ds.create_role(name='administrator', description='高级管理员') ds.commit() # 导入一些网站数据 # 添加一个系统管理员账户 print "init system finish"
def dropdb(force=False): """ Drops all database tables """ if force or prompt_bool("Are you sure you want to lose all your data"): db.drop_all()
def init_db(no_confirm=False, drop_all_tables=False): '''Create the database from scratch. This will DELETE any data already in the database. no_confirm will skip user confirmation drop_all_tables will reset the entire database, not just the table set in the app's config ''' # Unless the no_confirm parameter is true, prompt user for a response, converted to a boolean. # If the response is negative (false), cancel the operation and return. Otherwise, keeep going. if not no_confirm: try: if not prompt_bool( "This will DESTROY all data in database and download new data. Are you sure" ): print "Cancelled" return except EOFError: print "\nInvalid response. Aborting." return if drop_all_tables: drop_tables = db.engine.table_names() else: drop_tables = [sales_data.table] print "Dropping tables: %s" % drop_tables for table in drop_tables: try: db.engine.execute("DROP TABLE %s" % table) except SQLAlchemyError: # Raised if table doesn't exist print "(table %s does not exist)" % table print "\nInitializing database..." sales_data.create_from_scratch()
def static(path, input): '''Compile and collect static files''' log = logging.getLogger('webassets') log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) if exists(path): print('"{0}" directory already exists and will be erased'.format(path)) if input and not prompt_bool('Are you sure'): exit(-1) cmdenv = CommandLineEnvironment(assets, log) # cmdenv.clean() cmdenv.build(production=True) print('Deleting static directory {0}'.format(path)) shutil.rmtree(path) print('Copying assets into "{0}"'.format(path)) shutil.copytree(assets.directory, path) for prefix, source in manager.app.config['STATIC_DIRS']: print('Copying %s to %s', source, prefix) destination_path = join(path, prefix) if not exists(destination_path): makedirs(destination_path) for filename in iglob(join(source, '*')): print(filename) if isdir(filename): continue shutil.copy(filename, destination_path) # shutil.copy(static_dir, path) print('Done')
def remove(container_id): try: if prompt_bool("Are you sure?"): docker.remove_container(container_id) print '%s %s' % (ok(), 'Container %s removed' % container_id) except Exception, e: print '%s %s' % (ko(), e)
def initialize(name=None, delete=False): index_name = name or '-'.join([es.index_name, date.today().isoformat()]) log.info('Initiliazing index "{0}"'.format(index_name)) if es.indices.exists(index_name): if prompt_bool('Index {0} will be deleted, are you sure ?'.format(index_name)): es.indices.delete(index_name) else: exit(-1) mappings = [ (adapter.doc_type(), adapter.mapping) for adapter in adapter_catalog.values() if adapter.mapping ] with open(ANALYSIS_JSON) as analysis: es.indices.create(index_name, { 'mappings': dict(mappings), 'settings': {'analysis': json.load(analysis)}, }) for model, adapter in adapter_catalog.items(): log.info('Indexing {0} objects'.format(model.__name__)) qs = model.objects.visible() if hasattr(model.objects, 'visible') else model.objects for obj in qs.timeout(False): try: es.index(index=index_name, doc_type=adapter.doc_type(), id=obj.id, body=adapter.serialize(obj)) except: log.exception('Unable to index %s "%s"', model.__name__, str(obj.id)) log.info('Creating alias "{0}" index "{1}"'.format(es.index_name, index_name)) indices = es.indices.get_alias(name=es.index_name).keys() es.indices.put_alias(index=index_name, name=es.index_name) for index in indices: es.indices.delete_alias(index=index, name=es.index_name) if delete: es.indices.delete(index=index)
def run(self): if prompt_bool("Are you sure you want to lose all your data"): mtable = get_table('measurements') mtable.drop() ntable = get_table('notification_settings') ntable.drop() print("Tables dropped.")
def delete_all(): """ Deletes all users """ if prompt_bool( "Are you sure you want to delete all users? This cannot be undone." ): delete_all_users() print "All users have been deleted. You should run 'dan delete_all' now"
def dropdb(): ''' Kill off the darn db and start over `python manage.py dropdb` ''' if prompt_bool('Are you sure you want to lose all your data'): db.drop_all()
def drop(): """Drops database tables""" if prompt_bool("Are you sure you want to lose all your data"): from application.models.logic import Logic db.metadata.drop_all(db.engine, tables=[Logic.__table__]) db.drop_all() redis.flushall()
def init_data(): from imports import ( Widget,Article,Page, User,Setting,Type, Template,Tag,Role, Category,Block,Profile, ContactMessage) """Fish data for project""" if prompt_bool('Do you want to kill your db?'): if squ.database_exists(db.engine.url): squ.drop_database(db.engine.url) try: db.drop_all() except: pass try: squ.create_database(db.engine.url) db.create_all() except: pass user = User.query.filter(User.email=='*****@*****.**').first() if user is None: user = User(username='******', email='*****@*****.**', password='******') user.save()
def clear_db(): """Drops and creates all db tables. (DESTRUCTIVE).""" if prompt_bool("May I drop and re-create all database tables"): app.logger.info('dropping all tables...') db.drop_all() app.logger.info('creating all tables...') db.create_all()
def delete_all(): """ Deletes all collections """ if prompt_bool( "Are you sure you want to delete all collections? This cannot be undone." ): delete_all_collections() print "All collections have been deleted"
def create_new_user_with_default_password(user_name=None): """ask did you create it ret: None #skip create """ is_new_user = False # input user name if user_name is None: user_name = prompt("user name") # check user name user = User.query.filter_by(name=user_name).first() if user is not None: print("duplicate user name!") return None # confirm for human if not prompt_bool("[{}] is a new user name, did you create it?".format(user_name), default=True): return None # create it user = User(name=user_name, password="******") return user
def dropdb(): """Drops database tables""" if prompt_bool("Are you sure you want to lose all your data"): destroy_db() db.drop_all() db_setup() db.create_all()
def unsubscribe(email, host): ''' Unsubscribes an email by resetting the form to unconfirmed. User may get one more confirmation email, but if she doesn't confirm that will be it.''' form = None if email and host: form = Form.query.filter_by(email=email, host=host).first() elif email and not host: query = Form.query.filter_by(email=email) if query.count() == 1: form = query.first() elif query.count() > 1: for f in query.all(): print '-', f.host print 'More than one result for this email, specify the host.' elif host and not email: query = Form.query.filter_by(host=host) if query.count() == 1: form = query.first() elif query.count() > 1: for f in query.all(): print '-', f.email print 'More than one result for this host, specify the email.' if form: print 'unsubscribing the email %s from the form at %s' % (form.email, form.host) if prompt_bool('are you sure?'): form.confirmed = False form.confirm_sent = False app.DB.session.add(form) app.DB.session.commit() print 'success.'
def run(self): print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' print 'WARNING!!!!! YOU ARE ABOUT TO DELETE ALL ISSUES!!!!!' print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' c = prompt_bool('Are you sure you wish to continue?') if c: email = prompt('Enter your administrator email address: ') u = User.query.filter_by(email=email).first() if u and u.has_role('super'): password = prompt('Enter password: '******'Deleting `issue_creators` table' db.engine.execute(issues_creators.delete()) print 'Deleting `issues_bundles` table' db.engine.execute(issues_bundles.delete()) print 'Deleting `Issue Covers` table' IssueCover.query.delete() print 'Deleting all objects from `Issues` table' Issue.query.delete() db.session.commit() print 'All Issues have been deleted.' print 'You should delete the cover images from the store!' else: print 'Incorrect password, Aborting...' else: print 'User not found or is not an administrator, Aborting...' else: print 'Aborting...' return
def delete_events(): """ Deletes all events """ if prompt_bool( "Are you sure you want to delete all events? This cannot be undone." ): delete_all_events() print "All events have been deleted"
def delete_all(): """ Deletes all users """ if prompt_bool( "Are you sure you want to delete all committees? This cannot be undone." ): delete_all_dans() print "All committees have been deleted"
def run(self, length): if prompt_bool("Overwrite app.secret_key?"): app_secret_key = "SECRET_KEY" hashed = rnd(int(length)) nu_line = "{} = '{}'\n".format(app_secret_key, hashed) with open(self.config_file, 'r') as origin: old_data = origin.readlines() nu_content = ''.join(self.overwriteSecretKey(old_data)) nu_content += '\n\n' + nu_line with open(self.config_file, 'w') as modified: modified.write(nu_content) print("*" * 5, "New secret key inserted into {}".format(self.config_file), sep='\n', end='\n\n') print('-' * 5, "Key value = {}".format(hashed), sep='\n') return True print('No secret key generate. Cancelled.') return False
def dropdb(): """Drops all database tables.""" try: if prompt_bool("Are you sure you want to lose all your data"): db.drop_all() except Exception: pass
def delete_places(): """ Deletes all places """ if prompt_bool( "Are you sure you want to delete all places? This cannot be undone." ): delete_all_places() print "All places have been deleted"
def drop(): """Drops database tables""" if prompt_bool("Are you sure you want to lose all your data"): db.drop_all() print ('All tables are dropped.') return True return False
def revision(message): """Add a revision""" engine = get_engine() config, _ = get_alembic_config(engine) m = "--autogenerate" alembic_revision(config, message=message, autogenerate=prompt_bool(m, default=True))
def delete_superadmin(email): super_admin = SuperAdminService.get_by_email(email) if not super_admin: print('Super admin not found!') return if prompt_bool('Do you really want to delete this account? [y/n]'): SuperAdminService.delete(super_admin.id) print('Success!')
def ask_or_abort(fn, yes=False, msg=None): if not msg: msg = "Are you sure you want to alter {green}{name}{endc}".format( green='\033[92m', name=current_app.config['SOLR_URL'], endc='\033[0m') if yes or prompt_bool(msg): return fn() else: raise SystemExit('You changed your mind, exiting...')
def revision(message): """마이그레이션에 revision을 추가합니다. --autogenerate 물음에 긍정한다면 자동으로 마이그레이션 스크립트를 생성할 수 있습니다. """ m = "--autogenerate" alembic_revision(alembic_config(), message=message, autogenerate=prompt_bool(m, default=True))
def refresh_db(): if prompt_bool('Are you sure you want to lose all current data'): with app.app_context(): print('Dropping Tables') db.drop_all() print('Creating Tables') db.create_all() print('Refresh Complete')
def delete(username): "Delete a user" if prompt_bool("Are you sure you want to delete {}".format(username)): user = User.query.filter_by(username=username).first() if user: db.session.delete(user) db.session.commit() print "User '{}' deleted".format(username)
def syncdb(): for m in MODELS: print '- create:', m getattr(models, m).create_table(fail_silently=True) if prompt_bool('Create admin?', default=True): createadmin() else: print 'You can do it later with: ./manage.py createadmin'
def create_local_config(): """Generate a local_config.py with necessary settings""" local_config_path = os.path.join(app.root_path, '../config/local_config.py') if os.path.exists(local_config_path): app.logger.info("local_config.py exists") if not prompt_bool("Overwrite"): return config_items = {} if prompt_bool("Generate SECRET_KEY", True): config_items['SECRET_KEY'] = os.urandom(24).encode('hex') config_items['ACCOUNT_VERIFICATION_SECRET'] = os.urandom(24).encode('hex') else: app.logger.warn("OK. You'll need to include a SECRET_KEY in local_config.py for the app to run.") output = render_template('config/local_config.py.tmpl', config_items=config_items) with open(local_config_path, 'w') as lc: print >>lc, output app.logger.info("local_config.py created")
def drop(): """Drops database tables""" if prompt_bool("Are you sure you want to lose all your data"): db.drop_all() print('All tables are dropped.') return True return False
def quickstart(): "Richtet DB und FTP ein" if prompt_bool("Datenbank einrichten?"): populate() if not prompt_bool("FTP einrichten?"): return structure = { "Users": {}, "Libraries": {l.name: {} for l in Lang.query}, "Games": { str(g.id): {l.name: { "example_ai": {}, "ailib": {} } for l in Lang.query} for g in GameType.query }, "Data": {}, "AIs": {}, "Tournaments": {} } @ftp.safe def ftp_safe(): def f(k, v, path=""): p = path + k if not ftp.ftp_host.path.isdir(p): print("MKDIR:", p) ftp.ftp_host.mkdir(p) else: print("EXISTS:", p) for k, v in v.items(): f(k, v, p + "/") for k, v in structure.items(): f(k, v) print( "Vergess nicht das Standartbild in AIs/default.png zu setzen.") try: ftp_safe() except ftp.err: print("FTP-Zeugs hat nicht geklappt!")
def dropdb(force=False): "Drops database tables" exe = (True if force or prompt_bool('Are you sure you want to lose all your data?') else False) if exe: db.drop_all() print 'Database dropped, location:\r\n[%-10s] %s' % ( 'DEFAULT', app.config['SQLALCHEMY_DATABASE_URI'])
def drop_all(): """Drop all data from the current DB Context.""" if prompt_bool("Are you sure you want to lose all your data?"): with app.app_context(): current_app.db.drop_all() current_app.db.session.commit() else: exit(1)
def recreate_db(confirm=False): """ Recreates database tables """ if confirm or prompt_bool("Do you want to drop existing data?"): print "Dropping..." db.drop_all() print "Creating..." db.create_all()
def check_db(): test_categories = session.query(models.Categories).all() if not test_categories: if prompt_bool( 'There are no categories. Would you like to create categories?' ): create_categories() else: print "Categories are present" return